Ask Your Question
1

Rounding error in sqrt(2) in Sage

asked 2015-11-28 19:00:03 +0100

naderi gravatar image

updated 2015-11-30 08:32:22 +0100

slelievre gravatar image

In the following code,

sage: floor(sqrt(2)*sqrt(2.)/2)==1
True
sage: (sqrt(2.)*sqrt(2.)/2)==1.0
False
sage: (sqrt(2.)*sqrt(2.)/2)
1.00000000000000
sage :((2^(1/2.))== sqrt(2.))
True
sage: (((2.^(1/2))* sqrt(2.)) == 2.)
False

why is there an approximation error?

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2015-11-29 10:41:19 +0100

tmonteil gravatar image

updated 2015-11-30 08:28:46 +0100

slelievre gravatar image

When you write sqrt(2.), you define a floating-point approximation of $\sqrt{2}$ with 53 bits of precision. So, since $\sqrt{2}$ is not rational (hence not of the form p/2^53), there is a rounding, so there is no reason that at the end of the computation you will get an exact result. However, you can see that the error is very small:

sage: two = 2.
sage: two.parent()
Real Field with 53 bits of precision
sage: sqrt(two)
1.41421356237310
sage: sqrt(two).parent()
Real Field with 53 bits of precision
sage: sqrt(two)*sqrt(two)/2
1.00000000000000
sage: sqrt(two)*sqrt(two)/2 - 1
2.22044604925031e-16

If you want exact computation, you can define 2 as an integer:

sage: two = 2
sage: two.parent()
Integer Ring
sage: sqrt(two)
sqrt(2)
sage: sqrt(two).parent()
Symbolic Ring
sage: sqrt(two)*sqrt(two)/2
1
sage: sqrt(two)*sqrt(two)/2 == 1
1 == 1
sage: bool(sqrt(two)*sqrt(two)/2 == 1)
True

or as an algebraic number:

sage: two = AA(2)
sage: two.parent()
Algebraic Real Field
sage: sqrt(two)
1.414213562373095?
sage: sqrt(two).parent()
Algebraic Real Field
sage: sqrt(two)*sqrt(two)/2
1.000000000000000?
sage: sqrt(two)*sqrt(two)/2 == 1
True

If you still want to work with floating-point numbers, but want a guarantee on the error, you can work with real intervals:

sage: two = RIF(2)
sage: two.parent()
Real Interval Field with 53 bits of precision
sage: sqrt(two).parent()
Real Interval Field with 53 bits of precision
sage: sqrt(two)*sqrt(two)/2
1.000000000000000?
sage: sqrt(two)*sqrt(two)/2 == 1
False
sage: 1 in sqrt(two)*sqrt(two)/2
True
sage: (sqrt(two)*sqrt(two)/2).endpoints()
(0.999999999999999, 1.00000000000001)

If you want to increase the precision with more bits you can do:

sage: two = RealField(100)(2)
sage: two
2.0000000000000000000000000000
sage: two.parent()
Real Field with 100 bits of precision
sage: sqrt(two).parent()
Real Field with 100 bits of precision
edit flag offensive delete link more

Comments

1

Try it now.

kcrisman gravatar imagekcrisman ( 2015-11-30 14:49:24 +0100 )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: 2015-11-28 19:00:03 +0100

Seen: 605 times

Last updated: Nov 30 '15