Why rational products are not correctly handled

asked 2023-05-04 10:30:55 +0100

moon gravatar image

updated 2023-05-04 10:44:07 +0100

Hi there. I've got a strange behavior on a very simple case. This is just a little code that generates two rationals (a priori) and ask to return their product and display it as a rational. I put that in a loop and got strange results however only time to time. it doesn't look to me that it's deterministic. Who can help understanding and why not how to do it properly. Thanks

    for i in range(100):
    n1=randint(0,6)
    d1=randint(1,4)
    n2=randint(1,100)
    d2=randint(1,100)
    exp1 = str(n1)+"/"+str(d1)+"*"+str(n2)+"/"+str(d2) + " = " 
    exp2 = eval("Rational(" + str(n1)+"/"+str(d1)+"*"+str(n2)+"/"+str(d2) +")")
    print(exp1 + str(exp2))

ps: looks like the indentation is lost when I copy the code.

This is an edit. I thought may be a copy of some displays could help

    1/3*3/11=1/11
2/1*11/43=22/43
4/1*65/37=260/37
2/4*19/23=19/46
6/3*51/86=51/43
1/4*100/65=5/13
3/3*4/40=1/10
1/1*78/88=39/44
1/3*56/80=205041934254272/878751146804023
4/2*12/14=12/7
0/1*85/2=0
6/3*72/94=72/47
1/1*72/41=72/41
5/3*48/14=40/7
6/3*80/4=40
4/3*88/15=352/45
0/3*71/67=0
5/2*88/93=220/93
4/4*43/39=43/39
4/3*77/54=71651876916793/37687026170521
6/1*100/40=15
0/3*61/90=0
6/2*19/96=19/32
1/4*15/23=15/92
0/3*82/96=0
3/2*71/52=213/104
edit retag flag offensive close merge delete

Comments

1

Replace exp2 by

exp2 = QQ(n1/d1)*QQ(n2/d2)

and use

print(exp1 ,exp2)

To obtain repeatable results start from

set_random_seed(1e6)
achrzesz gravatar imageachrzesz ( 2023-05-04 11:34:23 +0100 )edit

@ achrzesz Thank you so much. however a bit frustrated as I didn't understood yet the why I got that random error.

moon gravatar imagemoon ( 2023-05-04 12:44:58 +0100 )edit

I don't understand why are you using strings to define multiplication of rationals. In your exp2 the character "*" is used but it is not the sign of multiplication of rationals but a string

achrzesz gravatar imageachrzesz ( 2023-05-04 12:47:38 +0100 )edit

My version can be reformulated as follows

exp2 = Rational(str(n1)+"/"+str(d1))*Rational(str(n2)+"/"+str(d2))
print(exp1,exp2)
achrzesz gravatar imageachrzesz ( 2023-05-04 13:18:23 +0100 )edit

to answer your question, yes here "*" is just a string. For whatever reason, I first generate my expressions/formulas etc and then evaluate them. Your answer works fine ! Thank you

moon gravatar imagemoon ( 2023-05-04 15:19:51 +0100 )edit