1

I have a matrix

M = np.array([
[1, -2, -2, -2, 1, 2],
[0, 3, -2, -3, 1, 3],
[3, 0, 0, 1, -1, 2],
[3, -3, -2, 0, 1, 1],
[0, -3, 3, -3, -3, 2]
])

and I'm trying to replace the first row by itself modulo some number N = 2497969412496091.

I've been playing around with this in the IDE for a while, and even though

>>> M[0] % N
           
array([1, 2497969412496089, 2497969412496089, 2497969412496089, 1, 2], dtype=int64)

After I preform M[0] = M[0] % N and print the matrix M, I get

>>> M[0]
           
array([1, -746726695, -746726695, -746726695, 1, 2])

I've also tried to copy the intermediate step M[0] % N in a temporary variable and then setting it equal to M[0] but the problem still persists. What is going on here?

0

1 Answer 1

1

Your array is np.int32:

print(type(M[0][0]))  # <class 'numpy.int32'>

Create the original array as np.int64 - to avoid getting integer overflow happening:

import numpy as np

M = np.array([
[1, -2, -2, -2, 1, 2],
[0, 3, -2, -3, 1, 3],
[3, 0, 0, 1, -1, 2],
[3, -3, -2, 0, 1, 1],
[0, -3, 3, -3, -3, 2]
], dtype=np.int64)

N = 2497969412496091
M[0] = M[0] % N

print(M)

Output:

[[ 1 2497969412496089 2497969412496089 2497969412496089       1            2]
 [ 0                3               -2               -3       1            3]
 [ 3                0                0                1      -1            2]
 [ 3               -3               -2                0       1            1]
 [ 0               -3                3               -3      -3            2]]
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, it seems to work fine after specifying dtype = np.int64. I just read the documentation for numpy.array and it says the default datatype is based on the minimum type required to hold the object, but how come it outputs the correct answer when I just do M[0] % N, even showing dtype = int64?
@Lig because you create a new array with numbers in it that do not fit int32 so it creates it as int64. Reasigning that to your old array does not change its datatype hence integer overflow

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.