Ask Your Question

AttributeError: 'int' object has no attribute 'inverse_mod'

asked 2016-06-04 14:46:45 +0200

fagui gravatar image

updated 2016-06-05 12:28:10 +0200

slelievre gravatar image

Hi i'm a beginner with Sage, and i have some trouble with types. It looks like the cause of my pain is trying to use numpy together with Sagemath, is it possible to use Sagemath without numpy?

Here is a small example of an error that i encounter, when trying to do simple modular calculations in GF(7).

I use the following code:

import numpy as np

for i in range(n):
for i in range(n):
for i in range(n):
    c[i]=tmp * (Li_ai[i]) * b[i].inverse_mod(p) %p

and I get the following error:

Traceback (most recent call last)
AttributeError: 'int' object has no attribute 'inverse_mod'
edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted

answered 2016-06-04 14:53:22 +0200

slelievre gravatar image

updated 2016-06-05 12:42:01 +0200

(Edited to answer the follow-up question posted as a comment.)

Your code uses numpy, which uses Python's int type.

Sage has its own type of integers, in addition to Python integers.

Sage methods such as inverse_mod are implemented for Sage integers, not Python integers.

You can convert a Python integer k to a Sage integer by calling Integer(k) or ZZ(k).

So, if you define, as in your code,

y =

then change the last line to


Better: directly define

y = ZZ(tmp)

and then do


Now, you might want to avoid numpy altogether and work with native Sage matrices and vectors.

You can initialize a matrix or vector by specifying the base ring (eg ZZ, QQ, etc), the dimension, and the entries. If you don't provide entries, you get a zero matrix or vector. Matrices and vectors are mutable by default.

Rows, columns, and vector components are indexed from 0 rather than 1.

sage: a = matrix(ZZ, 3)
sage: a
[0 0 0]
[0 0 0]
[0 0 0]
sage: a[0, 0] = 4
sage: a
[4 0 0]
[0 0 0]
[0 0 0]

sage: v = vector(ZZ, 3)
sage: v
(0, 0, 0)
sage: v[1] = 2
sage: v
(0, 2, 0)
sage: a * v
(0, 0, 0)

You can find lots more information and examples in the documentation and tutorials, eg

See also the quick reference manual

or query your favourite web search engine for [sagemath linear algebra].

edit flag offensive delete link more


thank you. how do i create an 0 matrix or vector of integers in SageMath ? is this object mutable ? (for example make an assignment M[1,2]=3)


fagui gravatar imagefagui ( 2016-06-05 06:14:26 +0200 )edit

I edited my answer to answer this follow-up question too.

slelievre gravatar imageslelievre ( 2016-08-23 09:57:24 +0200 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower


Asked: 2016-06-04 14:46:45 +0200

Seen: 2,398 times

Last updated: Jun 05 '16