138k views
5 votes
In numerical methods, one source of error occurs when we use an approximation for a mathematical expression that would otherwise be too costly to compute in terms of run-time or memory resources. One routine example is the approximation of infinite series by a finite series that mostly captures the important behavior of the infinite series.

In this problem you will implement an approximation to the exp(x) as represented by the following infinite series,
exp(x) = Infinity n= 0 xn/xn!
Your approximation will be a truncated finite series with N + 1 terms,
exp(x, N) = Infinityn n = 0 xn/xn!
For the first part of this problem, you are given a random real number x and will investigate how well a finite series expansion for exp(x) approximates the infinite series.
Compute exp(x) using a finite series approximation with N E [0, 9] N (i.e. is an integer).
Save the 10 floating point values from your approximation in a numpy array named exp_approx. exp_approx should be of shape (10,) and should be ordered with increasing N (i.e. the first entry of exp_approx should correspond to exp(x, N) when N = 0 and the last entry when N = 9).

1 Answer

4 votes

Answer:

The function in Python is as follows:

import math

import numpy as np

def exp(x):

mylist = []

for n in range(10):

num = (x**n)/(math.factorial(n))

mylist.append([num])

exp_approx = np.asarray(mylist)

sum = 0

for num in exp_approx:

sum+=num

return sum

Step-by-step explanation:

The imports the python math module

import math

The imports the python numpy module

import numpy as np

The function begins here

def exp(x):

This creates an empty list

mylist = []

This iterates from 0 to 9

for n in range(10):

This calculates each term of the series

num = (x**n)/(math.factorial(n))

This appends the term to list, mylist

mylist.append([num])

This appends all elements of mylist to numpy array, exp_approx

exp_approx = np.asarray(mylist)

This initializes the sum of the series to 0

sum = 0

This iterates through exp_approx

for num in exp_approx:

This adds all terms of the series

sum+=num

This returns the calculated sum

return sum

User Lockyer
by
5.1k points