1

I created the following piece of python code. It should first set the precision of numbers to 10 decimal digits, but printing pi shows 3.156, which only has 3 decimal digits! 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))
Olivier
  • 607
  • 1
  • 6
  • 21

1 Answers1

0

You can use the following function to get the gmpy2 precision according to the number of digits you want.

>>> 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.

>>> 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:

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

Note that, gmp_prec(20) returns 67.

Then, we can use the result as follow:

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

The above result is precise with 20 decimal places.

Reza K Ghazi
  • 347
  • 2
  • 9