简体   繁体   中英

Comparing two numbers in sage

i would like to know why by comparing two real numbers (eg bool(r1 == r2) ) in sage cas online it returns wrong boolean values.

Eg§1:

(x,y,z)=var('x,y,z');
x=2
r1= (sin(x)).n()
r2= (sin(x)).n(digits=3)
print r1, type(r1)
print r2, type(r2)
bool(r1==r2)

0.909297426825682 == 0.909 True

But Eg§2

(x,y,z)=var('x,y,z');
x=2
r1= (sin(x)).n()
r2= (0.909).n(digits=3)
print r1, type(r1)
print r2, type(r2)
bool(r1==r2)

0.909297426825682 == 0.909 False

Or eg§3

(x,y,z)=var('x,y,z');
x=2
r1= 0.909297426825682.n(digits=3)
r2= (0.909).n(digits=3)
print r1, type(r1)
print r2, type(r2)
bool(r1==r2)

0.909 == 0.909 False

In my project I would like to compare user answer which can be rounded eg to 3 decimal places with 53 bits CAS-solution solution which can be both symbolic and numeric values. Thanx

First note that declaring x,y,z to be variables is not what you want, because that is a symbolic variable; you can just do x=2 without prelude. That is not really relevant, but helpful, I hope.

As to your question, your numbers are actually subtly different. The way they print out is not the internal representation.

sage: s1= (sin(x)).n()
....: s2= (sin(x)).n(digits=3)
sage: r1= (sin(x)).n()
....: r2= (0.909).n(digits=3)
....: 
sage: s2 == r2
False
sage: s2 - r2
0.000305
sage: s2.sign_mantissa_exponent()
(1, 14898, -14)
sage: r2.sign_mantissa_exponent()
(1, 14893, -14)

You can see that they are represented slightly differently by the computer, presumably due to the original difference

sage: sin(2.)
0.909297426825682
sage: 0.909
0.909000000000000

Whereas

sage: r1 - s1
0.000000000000000

The way in which the digit precision works is not exactly the same as just truncation, and preserves a little extra info to keep things accurate.

Moral: Be very careful with numerical work unless you really understand that real numbers aren't the same as what's in the computer. Luckily, for most practical purposes John's comments will serve you just fine, or else I'd be in trouble, as someone who is definitely not a numerical analyst.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM