Java Floating-Point Comparison - double / float Variable Comparison with Epsilon - Java Programming

preview_player
Показать описание
Floating-point numbers should not be compared using == because some of these numbers cannot be exactly represented

You may expect them to be equal when comparing them, but instead they are just very close and == will come out as false

Therefore, floating-point numbers should not be compared for exact equality but instead for being close enough

The epsilon is a difference threshold for indicating that floating-point numbers are equal (it is usually 0.0001)

Java if else Statements

Java Relational Operators

Java Multi-branch if-else-if Statement

Java Nested if-else Statements

Java Distinct If Statements

Java Logical Operators

Java Short Circuit Evaluation

Java Switch Statement

Java Precedence Rules for Logical and Relational Operators

Java Boolean Data Type

Java String Comparison Methods

String Access Methods

String Modifier Methods

The Conditional Expression

Floating-point Comparison

Character Comparison

Displaying Currency in Java

Variable Scope
Рекомендации по теме
Комментарии
Автор

Please SUBSCRIBE! More programming videos coming soon! ✌️

Appficial
Автор

Thanks for the video. I really don't understand why this isn't taught earlier on in the educational process. I've been coding for a few years (as a hobby) and just recently found out about this.

AlexTechie
Автор

I was about to click like on it, but...mm, you got a NICE mate...

Mirtguitar
Автор

how would you use epsilon for comparing <= ?

blacklistjeol
Автор

public static double approx(double a) {
double epsilon =
if (Math.abs(a - Math.round(1000.0 * a) / 1000.0) <= epsilon)
return Math.round(1000.0 * a) / 1000.0;
else
return a;
//it just approximates to the nearest thousandths if and only if it is very close
//for eg gets approximated to 1 but 0.9 does not


}
public static BigDecimal approx(BigDecimal a) {
double epsilon =
if ((a.subtract(a.setScale(4, <= epsilon)
return a.setScale(4, RoundingMode.HALF_UP);
else
return a;

}
}

aahaanchawla
Автор

var result = (Math.abs(a - b) < EPSILON) ? "Same" : "Not the same";
System.out.println(result);

catharperfect
welcome to shbcf.ru