Timothy Lawman
Timothy Lawman

Reputation: 2312

Python Excel floating point big difference

I used the following code to compute square root in Python:

from math import *

#find average of two numbers
def average(a, b):
    print "the average is",(a + b) / 2.0,"\n"
    return (a + b) / 2.0


    #guess not good enouhgh
    def improve(guess, x):
        print "improved guess is ",average(guess, x/guess),"\n"
        return average(guess, x/guess)

    #As long as the guess is not good enough, keep on improving the guess
    def good_enough(guess, x):
        d = abs(guess*guess - x)
        print d," is the currentguess\n"
        return (d < 0.001)

    #As long as the guess is not good enough, keep on improving the guess
    def square_root(guess, x):
        while(not good_enough(guess, x)):
            guess = improve(guess, x)
            print "current guess is ",guess,"\n"
        return guess

    if __name__ == "__main__":
        x = square_root(5, 33)
        print "final answer is",x

The result of the square root of 33 was :5.74456521739

I used the square root function in excel 2003:

=sqrt(33)

setting result at 15 decimal places and got the result:5.744562646538030

I then used:

math.sqrt(33) 

from the standard Python 2.7.2 math library

and got the result: 5.74456264654

I then increased accuracy of my Program: return (d < 0.000001)

and got return 5.74456264654 the same as the my program

The question is why is Python rounding and Excel 2003 is rounding in different places. How can someone know which one is better to use in a critical situation? For example friends who are writing maths equations that need a high degree of accuracy in physics for a PHD thesis?

Upvotes: 2

Views: 2667

Answers (3)

Kenji Noguchi
Kenji Noguchi

Reputation: 1773

Python and Excel both uses double precision floating point, which the precision depends on underlying C library, and it normally uses the hardware floating point unit. Common FPU implements IEEE-754 double.

Having said that, I suspect you're using print statement which does the formatting. See the difference below.

>>> import math
>>> math.sqrt(33)
5.744562646538029
>>> print math.sqrt(33)
5.74456264654

Upvotes: 3

DhruvPathak
DhruvPathak

Reputation: 43255

It depends on the implementation. If you want to use inbuild module, use decimal module. Some external modules like :

mpmath : http://code.google.com/p/mpmath/

bigfloat : http://pythonhosted.org/bigfloat/

are also good.

Upvotes: 1

jamylak
jamylak

Reputation: 133624

You can use the decimal module to achieve this level of accuracy:

>>> import decimal
>>> decimal.getcontext().precision = 15
>>> decimal.Decimal(33).sqrt()
Decimal('5.744562646538028659850611468')

In regards to floating point inaccuracies: http://docs.python.org/2/tutorial/floatingpoint.html

Upvotes: 3

Related Questions