3

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]

{N[a],N[b]}

{0.57735,0.57735}

Now, a==b does not do anything.

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

True

False

False

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

Chop@N[a - b] == 0

True

However,

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?

Sumit
  • 15,912
  • 2
  • 31
  • 73

1 Answers1

7

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)]

False

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

Roman
  • 47,322
  • 2
  • 55
  • 121