Ask Your Question
1

why there is no exact result with this fractions sum ?

asked 2022-07-06 16:37:57 +0100

ryss gravatar image

Hi, here is my code, in order to use it with sagetex (I'm new with sage). I want to make a sum with two fractions.

L = random.sample([n for n in range(-15, 15) if n != -1 and n != 1 and n != 0], 4)
print(L)
print(type(L[0]))
L[0]/L[1]+L[2]/L[3]

and the result is :

[-11, 12, 7, -7]
<class 'int'>
-1.9166666666666665

so, no exact value.

I've made an other test :

L = random.sample([n for n in range(-15, 15) if n != -1 and n != 1 and n != 0],4)
print(L)
print(type(L[0]))
print(L[0]/L[1]+L[2]/L[3])
QQ(L[0]/L[1]+L[2]/L[3])

and the output is :

[-6, -8, -4, 5]
<class 'int'>
-0.050000000000000044
-52215647853572/1044312957071439

instead of -1/20. I would like to understand how to achieve the exact and simplified fraction.

Thank you


Edit :

I tried with this 1 min ago :

L = random.sample([n for n in range(-15, 15) if n != -1 and n != 1 and n != 0],4)
print(L)
print(type(L[0]))
print(L[0]/L[1]+L[2]/L[3])
print(Integer(L[0])/Integer(L[1])+Integer(L[2])/Integer(L[3]))
QQ(L[0]/L[1]+L[2]/L[3])

and the output is :

[5, -8, -6, -13]
<class 'int'>
-0.16346153846153844
-17/104

-39792720200266/243437817695745

so ... i have to do this with "Integer" ?

edit retag flag offensive close merge delete

Comments

Welcome to Ask Sage! Thank you for your question.

slelievre gravatar imageslelievre ( 2022-07-06 17:29:33 +0100 )edit

2 Answers

Sort by ยป oldest newest most voted
2

answered 2022-07-06 19:27:01 +0100

updated 2022-07-06 19:27:22 +0100

Yes, definitely use Integer to get access to exact arithmetic. Python isn't built for this, and int is a Python class. Sage and its Integer class are built for this. You could do L = random.sample([Integer(n) for n ...]), or use srange instead of range to iterate using the Integer class.

edit flag offensive delete link more

Comments

Thank you for the answer.

ryss gravatar imageryss ( 2022-07-07 13:56:27 +0100 )edit
1

answered 2022-07-06 20:50:20 +0100

Emmanuel Charpentier gravatar image

updated 2022-07-06 20:51:53 +0100

from srange? :

Docstring:     
   Return a list of numbers "start, start+step, ..., start+k*step",
   where "start+k*step < end" and "start+(k+1)*step >= end".

   This provides one way to iterate over Sage integers as opposed to
   Python int's.  It also allows you to specify step sizes for such an
   iteration.

HTH,

EDIT :

Just saw John Palmieri's suggestion, whi h amoiunts exactly to the same thing. Wups...

edit flag offensive delete link more

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: 2022-07-06 16:30:31 +0100

Seen: 142 times

Last updated: Jul 06 '22