Ask Your Question

Use of / operator when defining a function

asked 2018-10-10 14:07:28 -0500

anonymous user


Hello. I need a clarification on the behaviour of fractions. More precisely, I don't understand the behaviour of the / operator when used inside a def().

I noticed that / finds the integer part of the fraction when used inside a def:

def sumA():
      return [a,b,c,d,a/b + c/d]

Then sumA() the following result:

[8, 3, 9, 8, 3]

That is: 8/3 + 9/8 = 3. How can I make a/b + c/d work like a sum of fractions inside this function?

Oddly enough, the behaviour is different when generating random numbers a and b and adding 1/a + 1/b.

def sumB():
     return [a,b,1/a + 1/b]

This function adds the fractions in the correct way. The result of sumB() is

[5, 9, 14/45]

Finally, I noticed that writing a1/b + c1/d instead of a/b + c/d makes everything work like fractions:

    def sumC():
      return [a,b,c,d,a*1/b + c*1/d]

The result of sumC() is

 [6, 7, 5, 6, 71/42]
edit retag flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted

answered 2018-10-10 16:43:01 -0500

tmonteil gravatar image

This is because randint returns a Python int and not a Sage Integer, and the division of two Python ints leads to an int:

sage: type(randint(2,10))
<type 'int'>

sage: int(5) / int(3)

When you write 1/a, since the 1 is a Sage integer, then the coercion makes the division happen in the set od Sage integers, this explains why you got a rational number:

sage: type(1)
<type 'sage.rings.integer.Integer'>

sage: get_coercion_model().common_parent(1,int(3))
Integer Ring

If you want to get random Sage integers, you can either convert the int into Sage integers:

sage: a = ZZ(randint(2,10))
sage: a
sage: type(a)
<type 'sage.rings.integer.Integer'>

Or, you can ask Sage to produce a random integer:

sage: a = ZZ.random_element(2,11)
sage: a
sage: type(a)
<type 'sage.rings.integer.Integer'>

Note that i replaced the 10 by 11, since in the random_element of Sage, the right bound is excluded, while it is not with the randint function.

edit flag offensive delete link more


Thank you so much!

jcarrillo gravatar imagejcarrillo ( 2018-10-12 02:59:00 -0500 )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: 2018-10-10 14:07:28 -0500

Seen: 41 times

Last updated: Oct 10