2

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?

4

3 回答 3

3

您可以使用该decimal模块来实现此级别的准确度:

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

关于浮点不准确:http ://docs.python.org/2/tutorial/floatingpoint.html

于 2013-05-29T10:14:17.677 回答
3

Python 和 Excel 都使用双精度浮点,其精度取决于底层 C 库,通常使用硬件浮点单元。通用 FPU 实现 IEEE-754 double。

话虽如此,我怀疑您正在使用print进行格式化的语句。请参阅下面的区别。

>>> import math
>>> math.sqrt(33)
5.744562646538029
>>> print math.sqrt(33)
5.74456264654
于 2013-05-29T11:01:05.117 回答
1

这取决于实施。如果要使用内置模块,请使用decimal模块。一些外部模块,如:

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

大浮动: http ://pythonhosted.org/bigfloat/

也不错。

于 2013-05-29T10:16:47.227 回答