Often I need to generate some data using some symmetry operations and I usually keep them as exact expressions (for example, consider the points on a triangular grid {{-(1/2), Sqrt[3]/2}, {-(1/2), -(Sqrt[3]/2)}, {1, 0}, ...}) and I need to compare different points, something like if a1+b==a2. I am trying to find an efficient way to do that.

Consider this

a=-2/Sqrt[3] + Sqrt[3]
b=Sqrt[1/4 + (2/Sqrt[3] - Sqrt[3]/2)^2]



Now, a==b does not do anything.

N[a] == N[b]
N[a]-N[b] == 0
N[a - b] == 0




Because N[a-b]=-3.33067*10^-16. So the way out is

Chop@N[a - b] == 0



RepeatedTiming[N[a] == N[b]]
RepeatedTiming[Chop@N[a - b] == 0]

{5.4*10^-6, True}

{9.07*10^-6, True}

On the other hand,

a1 = N[a]; b1 = N[b];
RepeatedTiming[a1 == b1]

{2.7*10^-7, True}

So my questions are

  1. Is it better to use real numbers if I have to do such comparisons?

  2. What would be the best (least time consuming when dealing with a large number of inputs) way to compare exact expressions if I have to use exact expressions?

  • 2
    $\begingroup$ You'll want to be careful if you find cases like this. N[Sin[2017 2^(1/5)]] - N[-1] $\endgroup$ – J. M.'s discontentment Mar 8 '19 at 10:29
  • 1
    $\begingroup$ PossibleZeroQ could help. $\endgroup$ – Roman Mar 8 '19 at 10:48
  • $\begingroup$ @J.M. Damn, this almost integer stuff is fascinating. Thanks! $\endgroup$ – Rebel-Scum Mar 8 '19 at 16:00

PossibleZeroQ is rather fast and does precisely what you're looking for:

RepeatedTiming[PossibleZeroQ[a - b]]

{3.2*10^-6, True}

@JM's difficult case is handled correctly:

PossibleZeroQ[Sin[2017 2^(1/5)] - (-1)]


The limits of PossibleZeroQ can be fine-tuned with $MaxExtraPrecision.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.