Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Python lab 3 assignment 1
- #
- ### Part 1 ###
- # Define a function (using 'def') to calculate factorials
- # Write a loop to print x and factorial(x) for x from 0 to 10 inclusive
- def fact(x):
- result = 1
- if x == 0:
- result=1
- while x >0:
- result = result*x
- x = x - 1
- return result
- def factorial():
- x = 0
- while 0 <= x <= 10:
- print x, fact(x)
- x = x + 1
- factorial()
- #### Part 2 ####
- # Write a function here called 'sin3terms' to calculate sin(x) using 3 terms
- # in the Taylor expansion
- def sin3terms(x):
- y = x - (x**3)/fact(3) + (x**5)/fact(5)
- return y
- # This loop will print the value of sin3terms from 0 to 2pi
- print "Part 2"
- pi = 3.141592653589793
- x = 0.0
- while x < 2*pi:
- print x, sin3terms(x)
- x = x + 0.1*pi
- #### Part 3 ####
- # Write a function here called 'sinNterms' to calculate sin(x) using N terms
- # in the Taylor expansion. The first input should be the value of x, and the
- # second should be N.
- def sinNterms(x,N):
- n = 1
- y = 0
- while n <= N:
- u = (x**(1+2(n-1))/fact(1+2(n+1))) * (-1)**(n+1)
- y = y + u
- n = n + 1
- return y
- # This loop should print sin(2*pi) using from 1 to 9 terms
- print "Part 3"
- for i in range(1,10):
- print i, sinNterms(2*pi, i)
- #### Part 4 ####
- # Write a function "howManyTerms" to calculate the number of terms required
- # to calculate sin(x) to withtin an accuracy, a.
- # This imports the built-in "sin" function
- from math import *
- # Print out statements to answer questions 1 to 3:
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement