math.nroot [was Re: A brief question.]

Tom Anderson twic at urchin.earth.li
Sun Jul 3 05:56:42 EDT 2005


On Sun, 3 Jul 2005, Steven D'Aprano wrote:

> On Sun, 03 Jul 2005 02:22:23 +0200, Fredrik Johansson wrote:
>
>> On 7/3/05, Tom Anderson <twic at urchin.earth.li> wrote:
>>> That's one way. I'd do:
>>>
>>> root = value ** 0.5
>>>
>>> Does that mean we can expect Guido to drop math.sqrt in py3k? :)
>>
>> I'd rather like to see a well implemented math.nthroot. 64**(1/3.0)
>> gives 3.9999999999999996, and this error could be avoided.
>
> py> math.exp(math.log(64)/3.0)
> 4.0
>
> Success!!!

Eeeeeeenteresting. I have no idea why this works. Given that math.log is 
always going to be approximate for numbers which aren't rational powers of 
e (which, since e is transcendental, is all rational numbers, and 
therefore all python floats, isn't it?), i'd expect to get the same 
roundoff errors here as with exponentiation. Is it just that the errors 
are sufficiently smaller that it looks exact?

> Note how much simpler this would be if we could guarantee proper 
> infinities and NaNs in the code. We could turn a 23-line block to a 
> one-liner.

YES! This is something that winds me up no end; as far as i can tell, 
there is no clean programmatic way to make an inf or a NaN; in code i 
write which cares about such things, i have to start:

inf = 1e300 ** 1e300
nan = inf - inf

Every bloody time. I'm going to be buggered if python ever rolls out some 
sort of bigfloat support.

And then god forbid i should actually want to test if a number is NaN, 
since, bizarrely, (x == nan) is true for every x; instead, i have to 
write:

def isnan(x):
 	return (x == 0.0) and (x == 1.0)

The IEEE spec actually says that (x == nan) should be *false* for every x, 
including nan. I'm not sure if this is more or less stupid than what 
python does!

And while i'm ranting, how come these expressions aren't the same:

1e300 * 1e300
1e300 ** 2

And finally, does Guido know something about arithmetic that i don't, or 
is this expression:

-1.0 ** 0.5

Evaluated wrongly?

tom

-- 
Please! Undo clips before opening handle.



More information about the Python-list mailing list