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)