Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to calculate the Natural constant with High Precision by python

2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

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.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report