Get the App
SLTechnology News&Howtos  ›  Development  › 

How to calculate the Natural constant with High Precision by python

Shulou Source: shulou.com Published: 2022-05-31 16:44:16 09月28日 Update

This article introduces the relevant knowledge of "how to find the natural constant with high precision in python". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Taylor expansion and the solution of e

Do you know how to find the e in the computer?

It starts with the magical Taylor.

To put it simply, it is e, which can be expressed as:

Obviously, when n is small enough, the accuracy is already very high, and the following series is convergent and can be ignored. And this can obviously be calculated by a computer.

Python and the magical decimal

Many people are used to using python to calculate high-precision integers, because python integers are high-precision, but floating-point numbers are only 32 bits, where python provides a magical library "decimal", which allows you to specify the precision of decimals, equivalent to "high-precision decimals".

Calculate import decimalPrecision=20000decimal.getcontext (). Prec=Precision

We can set a precision for it like this.

Then it is followed by our expansion, which is generally close to the precision bit.

E=decimal.Decimal (0) nFrac=decimal.Decimal (1) for N in range (1): E+=nFrac nFrac/=Nprint (E)

The final effect is

A whole page of figures, after all, 20000 digits.

Compare

We use professional software "mathematica" to calculate the 20000 digits of e, and save it as a string and pass it to decimal. Here, we should note that we must use a string instead of directly writing the decimal, because the default decimal only 32bit will lose the remaining precision.

Tags: High precision high precision decimal magical only constant natural content character string that is integer more knowledge computer Taylor practical accurate learned. Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno OPPO Reno Huawei Shulou Tech Info MariaDB MySQL