以下示例查找 30 度的 cos 将帮助您了解如何做到这一点
>>> angle=30*math.pi/180 #30 degree in randian
>>> cosine = math.cos(angle) #Lets find the cosine of 30 degree
>>> #Square it. Helps to represent a range of irrational numbers to rational numbers
>>> cos2 = cosine ** 2
>>> # Lets drop some precision. Don't forget about float approximation
>>> cos2 = round(cos2,4)
>>> num = fractions.Fraction(cos2).numerator #Just the Numerator of the fraction
>>> den = fractions.Fraction(cos2).denominator #The denominator of the fraction
>>> def PerfSquare(n): #Square root in an Integer
return int(n**0.5)**2 == n
# If Perfect Square then Find the Square root or else represent as a root
>>> num = str(num**0.5) if PerfSquare(num) else "root{0}".format(num) # If Perfect Square then Find the Square root or else represent as a root
>>> den = str(den**0.5) if PerfSquare(den) else "root{0}".format(den)
>>> cos = "{0}/{1}".format(num,den) #Combine Numerator and Denominator
>>> print cos
root3/2.0
这里是按上述原理的一个函数
>>> HIGHVALUE=1000
>>> def foo(degree,trigfn):
angle=degree*math.pi/180 #in randian
trigval = trigfn(angle) #Lets find the trig function
#Square it. Helps to represent a range of irrational numbers to rational numbers
trigval2 = trigval ** 2
# Lets drop some precission. Don't forget about float aproximation
trigval2 = round(trigval2,5)
if trigval > HIGHVALUE:
return u'\u221e'
num = fractions.Fraction(trigval2).numerator #Just the Numerator of the fraction
den = fractions.Fraction(trigval2).denominator #The denominator of the fraction
if (num > HIGHVALUE or den > HIGHVALUE):
trigval2 = round(1/trigval2,4)
den = fractions.Fraction(trigval2).numerator #Just the Numerator of the fraction
num = fractions.Fraction(trigval2).denominator #The denominator of the fraction
if num > HIGHVALUE or den > HIGHVALUE or num < 1 or den < 1:
#Cannot be represented properly
#Just return the value
return str(round(trigval,4))
# If Perfect Square then Find the Square root or else represent as a root
num = str(int(num**0.5)) if PerfSquare(num) else u"\u221a{0}".format(num)
den = str(int(den**0.5)) if PerfSquare(den) else u"\u221a{0}".format(den)
return u"{0}".format(num) if den == "1" else u"{0}/{1}".format(num,den) #Combine Numerator and Denominator
运行的结果
>>> def Bar():
print 'Trig\t'+'\t'.join(str(x) for x in xrange(0,91,15))
for fn in [math.sin,math.cos,math.tan]:
print fn.__doc__.splitlines()[0],'\t',
print '\t'.join(foo(angle,fn) for angle in xrange(0,91,15) )
>>> Bar()
Trig 0 15 30 45 60 75 90
sin(x) 0.0 0.2588 1/2 1/√2 √3/2 0.9659 1
cos(x) 1 0.9659 √3/2 1/√2 1/2 0.2588 0.0
tan(x) 0.0 0.2679 1/√3 1 √3 3.7321 ∞