Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Rule 4.1.2: Numbers of a float type should not be directly compared with equality operator (==) or other methods like compareTo and equals. #290

Closed
petertrr opened this issue Sep 15, 2020 · 1 comment · Fixed by #323
Assignees
Labels
enhancement New feature or request
Milestone

Comments

@petertrr
Copy link
Member

Since floating-point numbers have precision problems in computer representation - as it was recommended in
Rule 4.1.1 - better to use BigDecimal instead when you need to make accurate computations and comparison.
The following code describes these problems:

val f1 = 1.0f - 0.9f
val f2 = 0.9f - 0.8f
if (f1 == f2) {
   println("Expected to enter here")
} else {
   println("But this block will be reached")
}

val flt1 = f1;
val flt2 = f2;
if (flt1.equals(flt2)) {
   println("Expected to enter here")
} else {
   println("But this block will be reached")
} 

Recommended example:

val foo = 1.03f
val bar = 0.42f
if (abs(foo - bar) > 1e-6f) {
    println("Ok")
} else {
    println("Not")
}
@petertrr petertrr added the enhancement New feature or request label Sep 15, 2020
@petertrr petertrr added this to the Chapter 4 milestone Sep 15, 2020
@petertrr petertrr self-assigned this Sep 22, 2020
@petertrr
Copy link
Member Author

Partially done in #303 , this part can be edited as follows:
'Binary operations on floats are prohibited, the only exception is comparison of absolute value of difference'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant