gmpy2 number(mpz) to mpf and back

67 views
Skip to first unread message

denis joubert

unread,
Apr 20, 2011, 11:45:43 AM4/20/11
to mpmath
Hello,

I found a way to convert mpz number (using gmpy2) to mpf
But now i'm looking to convert back an mpf to mpz number when mpf is a
big integer.
Could someone tell me how to do it ?

Thanks,

Denis

Fredrik Johansson

unread,
Apr 20, 2011, 12:04:47 PM4/20/11
to mpm...@googlegroups.com

Hi Denis,

If x is an mpf, mpz(int(x)) should work.

Fredrik

Fredrik Johansson

unread,
Apr 20, 2011, 12:58:01 PM4/20/11
to mpm...@googlegroups.com
On Wed, Apr 20, 2011 at 6:43 PM, denis joubert <denis....@gmail.com> wrote:
> Hello,
> No it doesn't work well on big number.
> Because a convertion to an int lost most digit.
> So why converting to mpz if you lost mpf bignum precision ???

I'm not sure if I understand. If the mpf is integer-valued nothing
will be lost. If it has fractional digits, those will of course be
lost. You can convert an mpf to a mantissa and exponent losslessly
like this:

>>> x = mpf(100.25)
>>> x.man_exp
(mpz(401), -2) # 100.25 = 401 * 2.0**(-2)

Or, if you want an integer representing the decimal value, just use
str() and remove the dot.

Fredrik

denis joubert

unread,
Apr 20, 2011, 12:43:50 PM4/20/11
to mpmath
Hello,
No it doesn't work well on big number.
Because a convertion to an int lost most digit.
So why converting to mpz if you lost mpf bignum precision ???

On Apr 20, 6:04 pm, Fredrik Johansson <fredrik.johans...@gmail.com>
wrote:

denis joubert

unread,
Apr 20, 2011, 1:26:51 PM4/20/11
to mpmath
Oh ok,

i used to think int type have a small storage(like under C langage).
But i tried with a 100000 digit numbers and nothing was lost.

Thanks a lot.

On Apr 20, 6:58 pm, Fredrik Johansson <fredrik.johans...@gmail.com>
wrote:
Reply all
Reply to author
Forward
0 new messages