java - Why EPSILON is used in comparing two floating point numbers -


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 of math.log10(n) / math.log10(3) 5.0000001 or 4.9999999. effect can observed using function math.log() instead of math.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

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -