Dosya
Dosya
Taylor Series
Objective
The goal of this assignment is to create a Python function that approximates
the sine function using the Taylor series expansion. This exercise will help you
practice using loops and functions in Python, with a particular focus on the
‘for’ loop and the ‘while’ loop.
Background
The sine function can be approximated using the Taylor series expansion:
x3 x5 x7
sin(x) ≈ x − + − + ...
3! 5! 7!
for small values of x, where:
• The terms alternate in sign.
Assignment Tasks
1. Write a Python function named sin taylor for that approximates the
sine of x using the first n terms of the Taylor series, implemented with a
‘for‘ loop and ‘range()‘.
2. Write another function named sin taylor while that does the same but
using a ‘while‘ loop.
1
3. Implement a helper function factorial(k) that computes the factorial of
k iteratively.
4. Test your functions using various values of x (e.g., 0.5, 1.0, 3.14) and
different numbers of terms (e.g., 3, 5, 10).
Template Code
1 import math
2
3 def factorial ( k ) :
4 # Implement the factorial function using a for loop
5 pass
6
7 def sin_taylor_for (x , n ) :
8 # Initialize the sine approximation
9 # Use a for loop with range () to iterate over n terms
10 # Compute each term using the Taylor series formula
11 # Add the term to the sine approximation
12 pass
13
14 def sin_taylor_while (x , n ) :
15 # Initialize the sine approximation
16 # Use a while loop to iterate over n terms
17 # Compute each term using the Taylor series formula
18 # Add the term to the sine approximation
19 pass
20
21 # Test cases
22 x = 1.57 # Example : approximating sin ( pi /2)
23 n = 5
24 print ( " Approximation using for loop : " , sin_taylor_for (x , n ) )
25 print ( " Approximation using while loop : " ,
sin_taylor_while (x , n ) )
26 print ( " math . sin : " , math . sin ( x ) )