'Using a function to calculate and print the value of the approximation for each value of n
I am struggling to use my function to calculate and print the values of the approximation for each value of n. I will also add the prompt that goes with the code.
Determine the number of terms in the expansion required to approximate cos(x) at x = 0.3π to 6 significant figures using the following Taylor series:
cos(x) ≈ 1 − x^2/2! + x^4/4! − x^6/6! + x^8/8! − … + (−1)^n*x^2n/(2n)!
Use the math module in Python to calculate cos(x) at x = 0.3π.
Write a user-defined function that takes x and n as inputs and calculates the approximation.
Use this function to calculate and print the value of the approximation for each value of n.
This is my code so far:
import math
# Using the math module in Python to calculate cos(x) at x = 0.3 pi
out = math.cos(0.3 * math.pi)
print("The value of cos(x) at x = 0.3pi is {:.6f}".format(out), "using math module in Python")
# Creating a function that will take inputs x and n and print out the approximate
# value of cos(x) = 0.3 pi
# Using a seperate variable for coefficient, numerator, and denominator
# Breaking the Taylor Series up into three parts to cut down on errors
def func_cos(x, n):
cos_approx = 0
for i in range(n):
coef = (-1)**i
num = x**(2 * i)
denom = math.factorial(2 * i)
cos_approx += (coef) * ((num) / (denom))
return cos_approx
# Asking user for inputs for x and n
x = float(input("Input x: "))
n = int(input("Input n: "))
print("The approximate value of cos(x) at x = 0.3 is {:.6f}".format(func_cos(x, n)), "using our user-defined function")
# Using the function to calculate the approxiation for each value of n
for i in range(1, n):
approx = func_cos
print(approx)
Solution 1:[1]
So, there's two things.
- You don't need
approxbut just to callfunc_cos(x,i). You need to call the function and to introduce its arguments. Otherwise you will just print the function itself, not its return value.
(notice that you're not using n within the for loop, but the value of i)
- You're also required to tell the required value of
nto approximate the value of cos(x) to certain significant figure, so I added abreakrulewithin the for loop you define to do it, that I think is self explanatory.
Love Fourier Series!! Let me know if this is what you need
out = math.cos(0.3 * math.pi)
print("The value of cos(x) at x = 0.3pi is {:.6f}".format(out), "using math module in Python")
# Creating a function that will take inputs x and n and print out the approximate
# value of cos(x) = 0.3 pi
# Using a seperate variable for coefficient, numerator, and denominator
# Breaking the Taylor Series up into three parts to cut down on errors
def func_cos(x, n):
cos_approx = 0
for i in range(n):
coef = (-1)**i
num = x**(2 * i)
denom = math.factorial(2 * i)
cos_approx += (coef) * ((num) / (denom))
return cos_approx
# Asking user for inputs for x and n
x = float(input("Input x: "))
n = int(input("Input n: "))
print("The approximate value of cos(x) at x = 0.3 is {:.6f}".format(func_cos(x, n)), "using our user-defined function")
# Using the function to calculate the approxiation for each value of n
m=30
for i in range(1, m):
if round(func_cos(x,i),6)==round(np.cos(x),6):
print(f'We required n={i} to approximate cos for 6 significant figures and x ={x}')
break
print(func_cos(x,i))
Solution 2:[2]
The trick for doing Taylor series like this is never to take a factorial. The quantity x**(2 * i) / math.factorial(2 * i) will very quickly become a problem because you won't be able to divide by the factorial meaningfully when it explodes. Instead, notice that each term in the sum is x**2 / (2 * i * (2 * i - 1)) times the previous one. Clearly this is a well bounded quantity that will go to zero quickly and manageably (since the series converges after all).
You can therefore write the loop as
def my_cos1(x, n=10):
cos_approx = 1
increment = 1
for i in range(1, n):
increment *= -0.5 * x**2 / (2 * i**2 - i)
cos_approx += increment
return cos_approx
But wait, there's more! Because of the way the sine and cosine series work, you don't need to check against a value you compute elsewhere. All you need to know is when increment drops below your target threshold (like the 1e-6 in the question):
def my_cos2(x, precision=1e-6):
cos_approx = 1
increment = 1
i = 1
while abs(increment) > precision:
increment *= -0.5 * x**2 / (2 * i**2 - i)
cos_approx += increment
i += 1
return cos_approx, i - 1
You will see this loop converge pretty quickly, and the value of i will tell you when that happens.
So here's a nice test. First print the "actual" value:
>>> from math import cos
>>> cos(0.3)
0.955336489125606
Now try to predict the number of iterations to get 1e-6 precision with my_cos2:
>>> value, iters = my_cos2(0.3, 1e-6)
>>> value
0.9553364891272321
>>> iters
4
Now you can use my_cos1 to show that after 3 iterations, the result is off by more than 1e-6, while after 4 iterations it's off by less:
>>> my_cos(0.3, 3) - cos(0.3)
1.0108743939696296e-06
>>> my_cos(0.3, 4) - cos(0.3)
-1.6256059831576408e-09
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | José Chamorro |
| Solution 2 |
