A Python program that computes the value of e using all three of the methods des
ID: 3770145 • Letter: A
Question
A Python program that computes the value of e using all three of the methods described below. Use values of 1, 2, 5, 10, 100, 1000, and 10000 for the first method, and values of n = 1,2,3,4,5,6,7,8,9,10, and 20 for the second method and values of n = 1, 3, 5, 7, and 9 for the third method. The program must print out the value of e computed with each value of n for each method and the difference with the value of in math library. Make certain that the outputs are labeled as to which method is being used and what value of n was used
Method 1: For example, the value of (1 + 1/n)n approaches e as n gets bigger and bigger: n (1 + 1/n)n 1 2.00000 2 2.25000 5 2.48832 10 2.59374 100 2.70481 1,000 2.71692 10,000 2.71815 100,000 2.71827 In the equations that follow, "!" means factorial. 0! = 1, 1! =1, 2! = 21 = 2, 3! = 321 = 6, 4! = 4321 = 24, 5! = 54321 = 120, etc.
Method 2: The Taylor series for the exponential function ex at a = 0 is If x is one, the value of e is equal to 1 + 1/1! + 1/2! + 1/3! + 1/4! + 1/5! + 1/6! + 1/7! + ... (etc) Another way of expressing this series is the formula: e=_(n=0)^1/n! The first few terms add up to: 1 + 1 + 1/2 + 1/6 + 1/24 + 1/120 = 2.718055556
Method 3: Recently, new formulae have been developed by Brothers (2004) makes the calculation of e very efficient.
e=_(n=0)^(2n+2)/(2n+1)!
Explanation / Answer
1)
Eular
import sympy as sy
import numpy as np
from sympy.functions import sin,cos
import matplotlib.pyplot as plt
plt.style.use("")
# Define the variable and the function to approximate
x = sy.Symbol('x')
f = sin(x)
# Factorial function
def factorial(n):
if n <= 0:
return 1
else:
return n*factorial(n-1)
# Taylor approximation at x0 of the function 'function'
def taylor(function,x0,n):
i = 0
p = 0
while i <= n:
p = p + (function.diff(x,i).subs(x,x0))/(factorial(i))*(x-x0)**i
i += 1
return p
2) Taylor Series
def sine(x):
sum = 0.0
n = 1
term = 1.0
while (term > .0000000001):
#loops until the iterations grow so large that 'term' becomes negligibly small
term = ((x ** (2 * n + 1.0))) / (factorial(2 * n + 1.0))
if n % 2 == 0:
sum += term
else:
sum -= term
n += 1
return sum
Pi Formula
import sys
import math
from decimal import *
def bbp(n):
pi = Decimal(0)
k = 0
while k < n:
pi += (Decimal(1)/(16**k))*((Decimal(3)/(8*k+1))-(Decimal(5)/(8*k+4))-(Decimal(7)/(8*k+5))-(Decimal(9)/(8*k+6)))
k += 1
return pi
def main(argv):
if len(argv) != 2:
sys.exit('')
getcontext().prec = (int(sys.argv[1]))
my_pi = bbp(int(sys.argv[2]))
accuracy = 100*(Decimal(math.pi)-my_pi)/my_pi
print "Pi is approximately " + str(my_pi)
print "Accuracy with math.pi: " + str(accuracy)
if __name__ == "__main__":
main(sys.argv[1:])
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.