Floating point module task

I have a problem with the floating point module in Python. This code:

...
print '(' + repr(olddir) + ' + ' + repr(self.colsize) + ') % (math.pi*2) = ' + repr((olddir+self.colsize)
...

Print

(6.281876310240881 + 0.001308996938995747) % (math.pi*2) = 2.9043434324194095e-13

I know that floating point numbers are not exact. But I can’t figure it out.

I don’t know if this is related in any way, but Google Calculator cannot handle this calculation. This is the result of Google Calculator:

(6.28187631024 + 0.001308996939) % (pi * 2) = 6.28318531

What causes this calculation error? And how can I avoid this in my Python program?

+3
source share
2 answers

Using a str()floating-point number for printing actually prints a rounded version of the number:

>>> print repr(math.pi)
3.1415926535897931
>>> print str(math.pi)
3.14159265359

, , , . , olddir+self.colsize , 2*math.pi, , Google Calculator, , 2*math.pi.

+4

str repr

>>> import scipy
>>> pi = scipy.pi
>>> str(pi)
'3.14159265359'
>>> repr(pi)
'3.1415926535897931'

str 12 , repr ( ).

EDIT: , - , - , . .

-, , ( ). (3.14 + 3.14)% (3.14 + 3.14), , , . , , ? (3.1 + 3.1)% (3.14 + 3.14) = 6.2% (6.28) = 6.2 ( Google). (3.14159,5) + (3.14159,5)% (3.14159 + 3.14159) = 6.2832% 6.28318 = 2e-5.

, N ( str, ), N . , ( ). , str 12, , , 10.

>>> round(6.28187631024 + 0.001308996939,10) % (round(pi * 2,10))
0
+2

All Articles