Python - Calculate The Base Of Natural Logarithm

用 Python 计算自然对数的底数——常数 e

Foreword

Constant e is the base of natural logarithm. Normally, we will only use its head few digits valuation.

In some situations, we may need to calculate a high precision e, or test performance of your computer, we could try to compute it by formula:

Code Example

from fractions import Fraction as F
from decimal import Decimal as D
from decimal import getcontext
from math import factorial as f

def calc(series: int, prec: int=300):
    getcontext().prec = prec
    e = 2
    for i in range(2, series + 1):
        e += F(1, f(i))
    # Convert Fraction to Decimal is not supported.
    return D(e.numerator)/ D(e.denominator)

NOTE: In the code, I reserve the use of fractions for the results to prevent loss of precision when converting to other types.

Usage

Call the function calc in your program.

Parameter intro

  • series: Specify how deep to calculate to
  • prec: Precision (digits) of decimal part.

Example

print(calc(100, 500))

Output

2.7182818284590452353602874713526624977572470936999595749669676277240766303535475945713821785251664274274663919320030599218174135966290435729003342952605956307380251882050351967424723324653614466387706813388353430034139974174573454428990064205056256412883731448662571812181695588396753195152779383841010625766452312821660523909839515512996947763023165855070702535657881114373508798119492923369289492218803532415232263419815664514069500471960037083157525314472746953376422185585970490727919479183987904
阅读剩余
THE END