floor() function and mathematical integers

Tim Peters tim.one at home.com
Fri May 25 04:11:22 EDT 2001


[Tim]
>> In context, I meant math.floor(x) returns the mathematically
>> correct result for every non-zero float x:  it introduces no
>> errors.  So when people

[Bengt Richter]
> UIAM, zero is ok too :)

Ack, yes.  I meant to type "finite", but I wrote the reply during a mtg I was
supposed to be paying attention to, and "finite" and "non-zero" apparently
meant the same thing to me at the time <wink>.

>> stumble into something like this:
>>
>>
>> >>> x = 32.05
>> >>> import math
>> >>> y = x * 100
>> >>> print y
>> 3205.0
>> >>> print math.floor(y)
>> 3204.0
>>
>> the last thing they should be looking at is the floor <wink>.

> This brings up the question of whether inexact print representations
> of internal values (which themselves are exact, whether they represent
> something else inexactly or not) should be flagged somehow by default.
>  >>> x = 32.05
>  >>> y = x * 100
>  >>> print y
>  3205.0
>  >>> y
>  3204.9999999999995
>  >>> print math.floor(y)
>  3204.0
>  >>>
> There's no surprise about floor(y) from the long representation.
> What if we got (e.g.)
>  >>> print y
>  3205.0'-
> to indicate that the internal value is really less,
> and 3205.0'+ if more ?
>
> Obviously, you'd want to be able to suppress this, but for interactive
> work, it would be less misleading and still fairly concise.

I'm afraid Python's a long way from being able to do this:  The internal
convert-to-string functions (Python-level repr() and str()) have no idea
whether they're being called in interactive or batch modes, and the printing
routine has no idea it's printing a float (it only sees a string).  In
addition, the actual conversion of float to string is handled by the platform
C library's sprintf, and even when platform C libraries set the inexact flag
correctly on to-string conversion, there's no portable way to get at the
inexact flag anyway.  So Python would need to grow mounds of f.p.
intelligence it doesn't have now.

In the past, when controlling my own conversions, I've added these tags to
float strings:

   +<h   true value larger than displayed, by less than 0.5 ULP
   +=h     "    "      "     "      "    , by exactly 0.5 ULP
   -=h     "    "   smaller  "      "    , by exactly 0.5 ULP
   -<h     "    "   smaller  "      "    , by less than 0.5 ULP

and +>h and ->h similarly (for use with directed rounding modes).  I found it
useful indeed!  But Python isn't likley to grow enough internal f.p. smarts
to do that itself, while C doesn't expose the info.

fp-will-break-your-heart-every-time<wink>-ly y'rs  - tim





More information about the Python-list mailing list