简体   繁体   English

如何使用 python 模块 gmpy2 将数字的精度设置为 10 位小数

[英]How can I set the precision of a number to have 10 decimal digits using the python module gmpy2

I created the following piece of python code.我创建了以下 python 代码。 It should first set the precision of numbers to 10 decimal digits, but printing pi shows 3.156, which only has 3 decimal digits.它应该首先将数字的精度设置为 10 位小数,但打印 pi 显示 3.156,它只有 3 位小数。 Would someone please let me know what I'm doing wrong.有人请让我知道我做错了什么。

import gmpy2 as g
from ipywidgets import widgets
from IPython.display import display

button = widgets.Button(description="Click Me!")
display(button)

max_precision = g.get_max_precision()
pi = g.const_pi()
g.set_context(g.context())

def set_bits_precision(decimal_precision):
    bits_precision = int(decimal_precision/g.log(2))
    if (bits_precision > max_precision): bits_precision = max_precision
    ctx = g.get_context()
    ctx.precision = bits_precision
    return

def square_root(number):
    return g.sqrt(number)

def circle_perimeter(radius):
    return 2*pi*radius 

def on_button_clicked(x):
    return square_root(x)

set_bits_precision(10)
print(pi)
button.on_click(on_button_clicked(2))

You can use the following function to get the gmpy2 precision according to the number of digits you want.你可以使用下面的function根据你想要的位数得到gmpy2精度。

>>> import gmpy2 as gmp

# n is the number of digits

>>> def gmp_prec(n): return int(n * gmp.log(10) / gmp.log(2)) + 1

Assume you need to set the correct precision of gmpy2 to get ten significant decimal digits then you can write.假设您需要设置gmpy2的正确精度以获得十位有效十进制数字,那么您可以编写。

>>> gmp.get_context().precision = gmp_prec(10)

For example, to calculate the sqrt of 2 by gmpy2 with the correct 20 digits after the decimal point, we have:例如,要通过gmpy2用正确的小数点后20位计算2sqrt ,我们有:

>>> gmp.get_context().precision = gmp_prec(20)

Note that, gmp_prec(20) returns 67 .请注意, gmp_prec(20)返回67

Then, we can use the result as follow:然后,我们可以使用如下结果:

>>> print(gmp.sqrt(2))
1.414213562373095048804

The above result is precise with 20 decimal places.上述结果精确到小数点后 20 位。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM