martedì 16 marzo 2010

how to calculate trigonometry with python

for that kind of jobs I can tell you it's more useful and faster C++ extensions than pure Python, but if you want do that in pure Python... I'll show you how to do that

#!/usr/bin/python
def ask():
...import math as m
...value_deg=int(raw_input("insert an angle value in degrees"))
...x=value_deg #I use that to write less...
...""" the formula with you can convert a degrees value in radians is
...deg:360=rad:2*PI --> rad=((deg*2/360)*PI) --> rad=((deg/180)*PI) """
...value_rad=(x/180.0)*3.14159) #I used 3.14159 for PI
...""" the sin(), cos() and tan() accept radians values only, and I round the
...printed value to five numbers"""
...#print sin of value_rad
...print round(m.sin(value_rad), 5)
...#print cos of value_rad
...print round(m.cos(value_rad), 5)
...#print tan of value_rad
...print round(m.tan(value_rad), 5)

I hope it's useful... Stay tuned!

2 commenti:

  1. use math.radians to convert degrees to radians and math.pi to have a good representations of pi.
    insert something like "While True", so it's more useful.something like:
    def ask():
    while True:
    val_deg = raw_input("insert an angle value in degrees")
    if val_deg.isdigit():
    val_deg = int(val_deg)
    val_rad = math.radians(val_deg)
    print 'Seno: %f' % round(math.sin(val_rad), 5)
    print 'Coseno : %f' % round(math.cos(val_rad), 5)
    print 'Tangente : %f' % round(math.tan(val_rad), 5)
    else:break
    bye

    RispondiElimina
  2. Thanks! I'll use this style forever!

    RispondiElimina