Hello, I am writing an application which uses the trig functions of the math module in python but for some reason, the float values that some of the calculations return are obviously incorrect. for example

math.cos(90*math.pi/180)

returns 6.1230317691118863e-17 rather than 0. Does anyone know of a way which I cant get this function to return an acurate value. I think the reason why it does not return 0 is because the value of the pi variable in the math module is not 100% accurate. Any ideas?

Recommended Answers

All 4 Replies

6.1230317691118863e-17

Note the e-17. This is a very small number and the closest that floating point numbers can come (similiar to converting 1/3 to a base 10 decimal). See here http://www.python.org/doc/faq/general/#why-are-floating-point-calculations-so-inaccurate and http://www.lahey.com/float.htm You have to use sloppy logic with floating point numbers

print "%10.7f" % ( math.cos(90*math.pi/180)) or
x = math.cos(90*math.pi/180)
if x < .00000000001:
   print "x = zero"

For greater precision you have to use Python's Deciimal module http://www.python.org/doc/2.5.2/lib/module-decimal.html but add on the trig functions from here http://pypi.python.org/pypi/AJDecimalMathAdditions/0.2.0 Also take a look at NumPy http://wiki.python.org/moin/NumPy This is the Numeric/Scientific Wiki http://wiki.python.org/moin/NumericAndScientific

Thanks, I don't think I'll use the decimal module, instead I'll check to see if the difference between two values is between a certain threshold rather than checking to see if they are equal.

This might help:

# see also: http://www.daniweb.com/forums/post896314-177.html

import math

def fuzzyequals(a, b, delta=0.0000000001):
    """
    returns true if a is between b-delta and b+delta
    used for comparison of floating point numbers a and b
    """
    return abs(a-b) < delta

# cosine of 90 degrees should be zero
n = math.cos(math.radians(90))
#n = math.cos(90*math.pi/180)

print(n)  # 6.12303176911e-17 close to zero, but not quite

if fuzzyequals(n, 0.0):
    n = 0.0

print(n)  # 0.0

Nice, thanks a lot for your help.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.