Underscores in Python numbers

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Bengt Richter

    #91
    Re: Underscores in Python numbers

    On Sun, 20 Nov 2005 15:37:40 +0000, Steve Holden <steve@holdenwe b.com> wrote:
    [color=blue]
    >David M. Cooke wrote:[color=green]
    >> Peter Hansen <peter@engcorp. com> writes:
    >>
    >>[color=darkred]
    >>>Steven D'Aprano wrote:
    >>>
    >>>>Dealing with numeric literals with lots of digits is
    >>>>a real (if not earth-shattering) human interface problem: it is hard for
    >>>>people to parse long numeric strings.
    >>>
    >>>I'm totally unconvinced that this _is_ a real problem, if we define
    >>>"real" as being even enough to jiggle my mouse, let alone shattering the
    >>>planet.
    >>>
    >>>What examples does anyone have of where it is necessary to define a
    >>>large number of large numeric literals? Isn't it the case that other
    >>>than the odd constants in various programs, defining a large number of
    >>>such values would be better done by creating a data file and parsing
    >>>it?[/color]
    >>
    >>
    >> One example I can think of is a large number of float constants used
    >> for some math routine. In that case they usually be a full 16 or 17
    >> digits. It'd be handy in that case to split into smaller groups to
    >> make it easier to match with tables where these constants may come
    >> from. Ex:
    >>
    >> def sinxx(x):
    >> "computes sin x/x for 0 <= x <= pi/2 to 2e-9"
    >> a2 = -0.16666 66664
    >> a4 = 0.00833 33315
    >> a6 = -0.00019 84090
    >> a8 = 0.00000 27526
    >> a10= -0.00000 00239
    >> x2 = x**2
    >> return 1. + x2*(a2 + x2*(a4 + x2*(a6 + x2*(a8 + x2*a10))))
    >>
    >> (or least that's what I like to write). Now, if I were going to higher
    >> precision, I'd have more digits of course.
    >>[/color]
    >Right, this is clearly such a frequent use case it's worth changing the
    >compiler for.
    >[/color]
    Agreed, let the OP hack a special-purpose solution for a special-case problem, e.g.
    (tested just enough to show the idea on this post ;-)
    [color=blue][color=green][color=darkred]
    >>> def fundef(funsrc, preprocess=None ):[/color][/color][/color]
    ... def doprep(f):
    ... protect_f = {}
    ... try:
    ... src = funsrc.lstrip() .rstrip()+'\n' # remove leading/trailing blank lines
    ... exec (preprocess and preprocess(src) or src) in protect_f
    ... return type(f)(protect _f[f.func_name].func_code,
    ... f.func_globals, f.func_name, f.func_defaults , f.func_closure)
    ... except Exception, e:
    ... raise ValueError, 'Unable to translate %r ... due to\n%s'%(
    ... funsrc.lstrip() .splitlines()[0][:30], '%s: %s'%(e.__class_ _.__name__, e))
    ... return doprep
    ...

    Now that decorator allows you to pre-process a function source
    (e.g. according to what the OP might want for a preprocess argument):
    [color=blue][color=green][color=darkred]
    >>> import re
    >>> numgap = re.compile(r'(\ d+) (?=\d)')
    >>> def prep(s): return numgap.sub(r'\1 ', s)[/color][/color][/color]
    ...

    Then use it on the OP's example [1]
    [color=blue][color=green][color=darkred]
    >>> @fundef("""[/color][/color][/color]
    ... def sinxx(x):
    ... "computes sin x/x for 0 <= x <= pi/2 to 2e-9"
    ... a2 = -0.16666 66664
    ... a4 = 0.00833 33315
    ... a6 = -0.00019 84090
    ... a8 = 0.00000 27526
    ... a10= -0.00000 00239
    ... x2 = x**2
    ... return 1. + x2*(a2 + x2*(a4 + x2*(a6 + x2*(a8 + x2*a10))))
    ... """, preprocess=prep )
    ... def sinxx(x): pass # (defines signature and defaults in current scope)
    ...

    [1] Note that no editing of previous source
    is required except bracketing like

    @fundef("""
    <previous source here>
    ... """, preprocess=prep )
    <def-line from previous source with pass after the ':'>

    That last line is required for the decorator, but also (I think, not tested) defines
    the signature and arg defaults in the current scope, as opposed to where exec compiles
    in the decorator.
    [color=blue][color=green][color=darkred]
    >>> sinxx[/color][/color][/color]
    <function sinxx at 0x02EFE4C4>[color=blue][color=green][color=darkred]
    >>> import math
    >>> def mxx(x): return x and math.sin(x)/x or 1.0[/color][/color][/color]
    ...[color=blue][color=green][color=darkred]
    >>> sinxx(0), mxx(0)[/color][/color][/color]
    (1.0, 1.0)[color=blue][color=green][color=darkred]
    >>> sinxx(.1), mxx(.1)[/color][/color][/color]
    (0.998334166470 76856, 0.9983341664682 8155)[color=blue][color=green][color=darkred]
    >>> sinxx(.2), mxx(.2)[/color][/color][/color]
    (0.993346653983 26816, 0.9933466539753 0608)[color=blue][color=green][color=darkred]
    >>>[/color][/color][/color]

    Seems to work, approximately ;-)
    [color=blue][color=green][color=darkred]
    >>> @fundef("""[/color][/color][/color]
    ... def poo()
    ... syntax problems
    ... """)
    ... def poo(): pass
    ...
    Traceback (most recent call last):
    File "<stdin>", line 1, in ?
    File "<stdin>", line 10, in doprep
    ValueError: Unable to translate 'def poo()' ... due to
    SyntaxError: invalid syntax (line 1)

    Some hope of somewhat useful exceptions too ;-)

    Regards,
    Bengt Richter

    Comment

    • Bengt Richter

      #92
      Re: Underscores in Python numbers

      On Sun, 20 Nov 2005 15:50:10 +0100, Eric Jacoboni <jaco@neottia.n et> wrote:
      [color=blue]
      >Mike Meyer <mwm@mired.or g> writes:
      >[color=green]
      >> I've seen at least one language (forget which one) that allowed such
      >> separators, but only for groups of three. So 123_456 would be valid,
      >> but 9_1 would be a syntax error.[/color]
      >
      >Ada allows underscores in numeric literals since 1983, without
      >enforcing any grouping. The Ruby language allows also this
      >notation. You may write 1_000_001 or 1000_001 or 10_00_001, etc. (the
      >same for real numbers...).
      >
      >When you have the habit to represent literals like that, all other
      >big numeric literals or workarounds to create grouping seem cryptic.
      >
      >--
      >Eric Jacoboni, ne il y a 1435938104 secondes[/color]
      Um, about your sig ... ;-)

      Regards,
      Bengt Richter

      Comment

      • Bengt Richter

        #93
        Re: Underscores in Python numbers

        On Sun, 20 Nov 2005 15:50:10 +0100, Eric Jacoboni <jaco@neottia.n et> wrote:
        [color=blue]
        >Mike Meyer <mwm@mired.or g> writes:
        >[color=green]
        >> I've seen at least one language (forget which one) that allowed such
        >> separators, but only for groups of three. So 123_456 would be valid,
        >> but 9_1 would be a syntax error.[/color]
        >
        >Ada allows underscores in numeric literals since 1983, without
        >enforcing any grouping. The Ruby language allows also this
        >notation. You may write 1_000_001 or 1000_001 or 10_00_001, etc. (the
        >same for real numbers...).
        >
        >When you have the habit to represent literals like that, all other
        >big numeric literals or workarounds to create grouping seem cryptic.
        >
        >--
        >Eric Jacoboni, ne il y a 1435938104 secondes[/color]
        Um, about your sig ... ;-)

        Regards,
        Bengt Richter

        Comment

        • Bengt Richter

          #94
          Re: Underscores in Python numbers

          On Sun, 20 Nov 2005 15:50:10 +0100, Eric Jacoboni <jaco@neottia.n et> wrote:
          [color=blue]
          >Mike Meyer <mwm@mired.or g> writes:
          >[color=green]
          >> I've seen at least one language (forget which one) that allowed such
          >> separators, but only for groups of three. So 123_456 would be valid,
          >> but 9_1 would be a syntax error.[/color]
          >
          >Ada allows underscores in numeric literals since 1983, without
          >enforcing any grouping. The Ruby language allows also this
          >notation. You may write 1_000_001 or 1000_001 or 10_00_001, etc. (the
          >same for real numbers...).
          >[/color]
          Actually, I guess I could be convinced, even though I posted a
          you-can-do-this-now decorator to bracket the op's desired function defs.
          [color=blue]
          >When you have the habit to represent literals like that, all other
          >big numeric literals or workarounds to create grouping seem cryptic.
          >
          >--
          >Eric Jacoboni, ne il y a 1435938104 secondes[/color]
          My previous smiley re your sig in this thread context still applies ;-)

          Regards,
          Bengt Richter

          Comment

          • Bengt Richter

            #95
            Re: Underscores in Python numbers

            On Sun, 20 Nov 2005 15:50:10 +0100, Eric Jacoboni <jaco@neottia.n et> wrote:
            [color=blue]
            >Mike Meyer <mwm@mired.or g> writes:
            >[color=green]
            >> I've seen at least one language (forget which one) that allowed such
            >> separators, but only for groups of three. So 123_456 would be valid,
            >> but 9_1 would be a syntax error.[/color]
            >
            >Ada allows underscores in numeric literals since 1983, without
            >enforcing any grouping. The Ruby language allows also this
            >notation. You may write 1_000_001 or 1000_001 or 10_00_001, etc. (the
            >same for real numbers...).
            >[/color]
            Actually, I guess I could be convinced, even though I posted a
            you-can-do-this-now decorator to bracket the op's desired function defs.
            [color=blue]
            >When you have the habit to represent literals like that, all other
            >big numeric literals or workarounds to create grouping seem cryptic.
            >
            >--
            >Eric Jacoboni, ne il y a 1435938104 secondes[/color]
            My previous smiley re your sig in this thread context still applies ;-)

            Regards,
            Bengt Richter

            Comment

            • bearophileHUGS@lycos.com

              #96
              Re: Underscores in Python numbers

              Peter Hansen>Or maybe one should instead interpret this as "numeric
              literals need more bells and whistles, and I don't care which of these
              two we add, but we have to do *something*!". :-)

              The purpose of my words was: when you think about adding a new
              syntax/functionality to a language, you have to think well if the same
              syntax can be used for something more important or more natural for it,
              so later you can avoid later problems and silly compromises.

              Bye,
              bearophile

              Comment

              • bearophileHUGS@lycos.com

                #97
                Re: Underscores in Python numbers

                Peter Hansen>Or maybe one should instead interpret this as "numeric
                literals need more bells and whistles, and I don't care which of these
                two we add, but we have to do *something*!". :-)

                The purpose of my words was: when you think about adding a new
                syntax/functionality to a language, you have to think well if the same
                syntax can be used for something more important or more natural for it,
                so later you can avoid later problems and silly compromises.

                Bye,
                bearophile

                Comment

                Working...