i'm googling how find if number y
power of x
, came across link
java
public class solution { public boolean ispowerofthree(int n) { return (math.log10(n) / math.log10(3)) % 1 == 0; } }
common pitfalls
this solution problematic because start using doubles, means subject precision errors. means, should never use
==
when comparing doubles. because result ofmath.log10(n) / math.log10(3)
5.0000001
or4.9999999
. effect can observed using functionmath.log()
instead ofmath.log10()
.in order fix that, need compare result against
epsilon
.java
return (math.log(n) / math.log(3) + epsilon) % 1 <= 2 * epsilon;
there didn't understand return (math.log(n) / math.log(3) + epsilon) % 1 <= 2 * epsilon;
what meaning of line?
why epsilon
used while comparing floating points?
as quoted section says, because of floating point imprecisions, can have 2 numbers should equal (if calculations created them carried out mathematical exactness), instead different.
when compare them, want account slight difference , still treat numbers equal if differ small amount, called epsilon.
how choose appropriate epsilon, though, tricky question , highly dependent on nature of calculations. suppose reason, java not include "standard" epsilon constant (some other languages do).
Comments
Post a Comment