python's round() function not working?

python

Solution

By deafault python's print rounds numbers to 11 digits when printing. Try instead

print '%0.12f'%n

To be a little more clear, when you are in the interactive console and do:

>>> x = 1.123456789012345
>>> x
1.123456789012345
>>> print x
1.12345678901

Remember that the the first call is actually a call to

x.__repr__() 

which will print as much information about x as it can, while the print statement translates to

print x.__str__()

and the builting str() method on ints rounds to 11 digits if necessary. You can force as many digits as you like using python's % formatting as shown above.

Problem

below is my program for finding approximate root for a some 5000th-degree polynomial that is given as a series: ``` def s(r, z): sm = 0 for k in range(1, z+1): sm += (900-3*k) * r ** (k-1) return sm target = -600000000000 n = 1 dr = .125 curr = 0 while abs(curr - target) > 1: curr = s(n, 5000) if curr > target : n+= dr else : n-=dr dr /= 2 ``` I wanted it rounded to 12 digits behind decimal point, hence ``` print round(n, 12) ``` which gave me : ``` 1.00232210863 ``` number is approximate enough, but it is now rounded to 12 digits. I fired up python console and found it myself : ``` >>> n 1.0023221086328755 >>> round(n, 12) 1.002322108633 ``` Why is my round() function working only inside python console prompt?

Original source