Ask Your Question
1

Why is a==b False?

asked 2017-12-09 00:46:54 +0100

Kapcak gravatar image

Please see the following code. Why is a==b False? Thanks!

Input:

a=n(1/2*sqrt(5) - 1/2,digits=15)
b=n(1-a^2,digits=15)
print a
print b
a==b

Output:

0.618033988749895
0.618033988749895
False
edit retag flag offensive close merge delete

1 Answer

Sort by » oldest newest most voted
3

answered 2017-12-09 07:34:59 +0100

slelievre gravatar image

This comes from working with numerical approximations.

In the computer, a and b are represented in binary. They are very close but not equal.

sage: a.sign_mantissa_exponent()
(1, 11133510565745312, -54)
sage: b.sign_mantissa_exponent()
(1, 11133510565745310, -54)

But the difference is very small and their decimal expansions to 15 digits coincide.

Sage lets you work with exact algebraic numbers, either by creating a number field:

sage: K.<a> = NumberField(x^2 + x - 1, embedding=0.6)
sage: a.numerical_approx()
0.618033988749895
sage: 1 - a^2
a

or by using the field of algebraic number (QQbar in Sage):

sage: a = QQbar(1/2*sqrt(5) - 1/2)
sage: a
0.618033988749895?
sage: 1 - a^2 == a
True
sage: a.minpoly()
x^2 + x - 1
sage: a.numerical_approx()
0.618033988749895
sage: a.radical_expression()
1/2*sqrt(5) - 1/2
edit flag offensive delete link more

Comments

3

Note that even without defining the corresponding number field or working in QQbar, SageMath correctly finds that a == b if you are not working with approximations but with exact symbolic expressions¹:

sage: a = 1/2*sqrt(5) - 1/2
sage: b = 1 - a^2
sage: bool(a == b)
True

¹ Note the necessity of calling bool(a==b) since a == b is kept as an expression by default, and one has to explicitly asks whether this equality holds.

B r u n o gravatar imageB r u n o ( 2017-12-09 12:00:39 +0100 )edit

Thank you both for your helpful replies!

Kapcak gravatar imageKapcak ( 2017-12-09 12:01:19 +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: 2017-12-09 00:45:51 +0100

Seen: 358 times

Last updated: Dec 09 '17