Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

conversion float to long in python

I have a function fac(n) which return n!, and I am comparing it to gamma(n+1)

>>> from math import gamma
>>> gamma(101)-fac(100)
0.0
>>> math.floor(gamma(101))-fac(100)
0.0
>>> long(gamma(101))-fac(100)
-1716052534060312817912314997891197522637580074354635372754659484313875350886868191008427848256820699487696649234627144617147818134104040275968L

gamma(101) = 100! and is an integer.

why are the results different ?

like image 368
Ricky Bobby Avatar asked Feb 24 '23 01:02

Ricky Bobby


2 Answers

The results are different because of the limited precision of the floating point type, and because of the way the subtraction operator coerces its operands to be the same type. The gamma function returns a float, so it cannot return an accurate answer for numbers this large. This page gives a good description of the issues.

In gamma(101)-fac(100) the fac(100) term is converted to a float before the subtraction operation.

>>> gamma(101)
9.332621544394415e+157
>>> float(fac(100))
9.332621544394415e+157

The (most significant) part of fac(100) that fits in a float matches that of gamma(101), so the subtraction results in 0.0.

For your second test, gamma(101) has no fractional part so math.floor has no effect:

>>> math.floor(gamma(101)) == gamma(101)
True

When you convert gamma(101) to a long you can clearly see that it's inaccurate:

>>> long(gamma(101))
933262154439441509656467047959538825784009703731840988
310128895405822272385704312950661130892883272778258496
64006524270554535976289719382852181865895959724032L
>>> fac(100)
933262154439441526816992388562667004907159682643816214
685929638952175999932299156089414639761565182862536979
20827223758251185210916864000000000000000000000000L
like image 93
Dave Avatar answered Feb 25 '23 15:02

Dave


Floating point numbers do not have infinite precision, and converting them to long will not give perfectly accurate results. The difference you're seeing is the difference between the floating point representation of gamma(101) and its actual integer value.

like image 34
Wooble Avatar answered Feb 25 '23 16:02

Wooble