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
版权声明
作者:灰尘疾客
链接:https://www.gkcoll.xyz/548.html
来源:极客藏源
注意:若文章头部无特殊声明,则文章为作者原创,版权归作者所有,未经允许请勿转载(默认允许)。
转载须知:若无特殊说明,本站所有文章均遵循 CC BY-NC-SA 4.0 协议发布,转载、二次创作请遵守该协议内容,并参考以下文案添加转载声明:本文转载自网站 极客藏源 的用户 @灰尘疾客 的文章 《Python - Calculate The Base Of Natural Logarithm》。本转载文发布遵循与原文相同的 CC BY-NC-SA 4.0 协议
THE END
分享
二维码
海报
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 valuat……
<<上一篇
下一篇>>