Ask Your Question

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

asked 2016-06-04 07:46:45 -0600

fagui gravatar image

updated 2016-06-05 05:28:10 -0600

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 07:53:22 -0600

updated 2016-06-05 05:42:01 -0600

(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-04 23:14:26 -0600 )edit

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

slelievre gravatar imageslelievre ( 2016-08-23 02:57:24 -0600 )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 07:46:45 -0600

Seen: 207 times

Last updated: Jun 05 '16