import math def main(): x = input('Enter value to get sine of in radians: ') if 0 <= x <= 2*math.pi: n = input('Enter number of iterations for approximation: ') total = 0.0 fac = 1 xp = x sign = 1 for i in range(1, 2*n, 2): total += sign * xp / fac xp *= x ** 2 fac *= (i+1)*(i+2) sign *= -1 real_sin = math.sin(x) print 'The approximated value of the sine of', x, 'is:', total print 'The actual value from math.sin is:', real_sin if real_sin != 0: print 'The relative error is:', abs(real_sin - total) / real_sin else: print 'x is an illegal value.' else: print 'The absolute error is:', abs(real_sin - total) main()
import random import math def main(): # You didn't know how to do the below loop for this problem set, but you # should know what it does now. It creates a list that contains all of # the number of iterations you were supposed to test. Try it! for n in [10, 100, 1000, 10000, 100000, 1000000]: total = 0 for i in xrange(n): x, y = random.random(), random.random() if math.sqrt(x ** 2 + y ** 2) < 1.0: total += 1 mypi = 4.0*total / n print 'Estimating pi with', n, 'iterations:', mypi print 'Value of math.pi is', math.pi print 'Error is', abs(math.pi - mypi) / math.pi print main()