Q:

Create a Python project to get the value of e to n number of decimal places. Note: Input a number and the program will generate e to the 'nth digit

0

Create a Python project to get the value of e to n number of decimal places.
Note: Input a number and the program will generate e to the 'nth digit.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

# https://github.com/microice333/Python-projects/blob/master/n_digit_e.py
# find e to nth digit by brothers' formulae: http://www.intmath.com/exponential-logarithmic-functions/calculating-e.php
import decimal


def factorial(n):
    factorials = [1]
    for i in range(1, n + 1):
        factorials.append(factorials[i - 1] * i)
    return factorials


def compute_e(n):
    decimal.getcontext().prec = n + 1
    e = 2
    factorials = factorial(2 * n + 1)
    for i in range(1, n + 1):
        counter = 2 * i + 2
        denominator = factorials[2 * i + 1]
        e += decimal.Decimal(counter / denominator)
    return e


while True:
    n = int(input("Please type number between 0-1000: "))
    if n >= 0 and n <= 1000:
        break

print(str(compute_e(n))[:n + 1])

Sample Output:

Please type number between 0-1000: 8
2.7182818

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Similar questions


need a help?


find thousands of online teachers now