-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtrig.py
95 lines (73 loc) · 2.36 KB
/
trig.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
# File: trig.py
# Author: Simon Chu
# Date: March 29 2017
# Purpose: use infinite series given to
# calculate sin and cos of x
from math import *
def intro():
print()
print("Program to approximate sin and cos.")
print("You will be asked to enter an angle and")
print("Written by Simon Chu")
print()
def getInputs():
angle = float(input("Enter an angle (in degrees): "))
print() # for turnin
terms = int(input("Enter the number of terms to use: "))
print()
print() # for turnin
return angle, terms
def factor(n):
fact = 1
for num in range(n, 0, -1):
fact = fact * num
return fact
def sinCalc(x, terms):
times = 0
approxSin = 0
for n in range(1, 2 * terms, 2):
times = times + 1
if times % 2 == 1:
fact = factor(n)
approxSin = approxSin + (x ** n) / fact
if times % 2 == 0:
fact = factor(n)
approxSin = approxSin - (x ** n) / fact
actualSin = sin(x)
differSin = abs(actualSin - approxSin)
return approxSin, actualSin, differSin
def cosCalc(x, terms):
times = 0
approxCos = 1
for n in range(2, 2 * terms - 1, 2):
times = times + 1
if times % 2 == 1:
fact = factor(n)
approxCos = approxCos - (x ** n) / fact
if times % 2 == 0:
fact = factor(n)
approxCos = approxCos + (x ** n) / fact
actualCos = cos(x)
differCos = abs(actualCos - approxCos)
return approxCos, actualCos, differCos
def printResult(angle, approxSin, approxCos, actualSin,
actualCos, differSin, differCos):
angle = int(angle)
print()
print("Function ", "Approx. Value ",
"Actual Value", " " * 3, "Difference")
print("sin(" + str(angle) + ") ", "{0:0.12f} {1:0.12f} "
"{2:0.12f}".format(approxSin, actualSin, differSin))
print("cos(" + str(angle) + ") ", "{0:0.12f} {1:0.12f} "
"{2:0.12f}".format(approxCos, actualCos, differCos))
print()
def main():
intro()
angle, terms = getInputs()
x = angle * pi / 180.0
print("For", terms, "terms:")
approxSin, actualSin, differSin = sinCalc(x, terms)
approxCos, actualCos, differCos = cosCalc(x, terms)
printResult(angle, approxSin, approxCos, actualSin,
actualCos, differSin, differCos)
main()