aleaxit / gmpy

General Multi-Precision arithmetic for Python 2.6+/3+ (GMP, MPIR, MPFR, MPC)
https://gmpy2.readthedocs.io/en/latest/
GNU Lesser General Public License v3.0
515 stars 86 forks source link

Strange behavior with in-place modifiable xmpz #115

Open agroce opened 8 years ago

agroce commented 8 years ago

Random testing of xmpz has not turned up many failures in a couple of hours, but one behavior is very strange. This is a cleaned up version of the auto-generated/reduced test. I don't seem to be doing any in place modification here, but the behavior is very different than with mpz. Changing val7 to an mpz makes no difference.

import gmpy2 from gmpy2 import mpz,mpq,mpfr,mpc,xmpz

print '''val3 = xmpz(2) ''' val3 = xmpz(2) val_REF3 = int(2) print '''val7 = xmpz(8) ''' val7 = xmpz(8) val_REF7 = int(8) print "val7",val7 print "val3",val3 print '''val7 = ~(val3) ''' val7 = ~(val3) val_REF7 = ~(val_REF3) print "val7",val7,val_REF7 print "val3",val3,val_REF3 assert (val3 == val_REF3)

print "TEST COMPLETED SUCCESSFULLY"

agroce commented 8 years ago

Or is ~(xmpz) supposed to in place modify?

casevh commented 8 years ago

~(xmpz) is supposed to modify in-place. xmpz is a mutable integer type and has some surprising properties. I originally wrote it to test if mutable types were faster. They aren't appreciably faster. They most practical use for them is their support of in-place bit manipulations and bit iteration. Here is simple and very fast Sieve of Eratosthenes:

def sieve(limit=1000000): sieve_limit = gmpy2.isqrt(limit) + 1 limit += 1

# Mark bit positions 0 and 1 as not prime.
bitmap = gmpy2.xmpz(3)

# Process 2 separately. This allows us to use p+p for the step size
# when sieving the remaining primes.
bitmap[4 : limit : 2] = -1

# Sieve the remaining primes.
for p in bitmap.iter_clear(3, sieve_limit):
    bitmap[p*p : limit : p+p] = -1

return bitmap.iter_clear(2, limit)

Thanks for all your testing!

Case

On Sat, Aug 27, 2016 at 8:48 PM, agroce notifications@github.com wrote:

Or is ~(xmpz) supposed to in place modify?

— You are receiving this because you are subscribed to this thread. Reply to this email directly, view it on GitHub https://github.com/aleaxit/gmpy/issues/115#issuecomment-242954527, or mute the thread https://github.com/notifications/unsubscribe-auth/ABkdb43XkJVFPFg36B8EkDA4_C-04Rirks5qkQUVgaJpZM4Ju1to .