Ask Your Question
1

Use of / operator when defining a function

asked 2018-10-10 21:07:28 +0200

anonymous user

Anonymous

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():
      a=randint(2,10)
      b=randint(2,10)
      c=randint(3,10)
      d=randint(4,10)
      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():
     a=randint(2,10)
     b=randint(2,10)
     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():
      a=randint(2,10)
      b=randint(2,10)
      c=randint(3,10)
      d=randint(4,10)
      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
1

answered 2018-10-10 23:43:01 +0200

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)
1

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
5
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
9
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

Comments

Thank you so much!

jcarrillo gravatar imagejcarrillo ( 2018-10-12 09:59:00 +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

Stats

Asked: 2018-10-10 21:07:28 +0200

Seen: 236 times

Last updated: Oct 10 '18