Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the best way to determine is a double is not zero

Tags:

c#

.net

Any suggestion on determining a double is not zero?

like image 463
user496949 Avatar asked Dec 30 '10 06:12

user496949


People also ask

How do you know if a double is zero?

if(value != 0) //divide by value is safe when value is not exactly zero. Otherwise when checking if a floating point value like double or float is 0, an error threshold is used to detect if the value is near 0, but not quite 0. Save this answer.

Can you use == to compare doubles in Java?

Using the == Operator As a result, we can't have an exact representation of most double values in our computers. They must be rounded to be saved. In that case, comparing both values with the == operator would produce a wrong result. For this reason, we must use a more complex comparison algorithm.

How do you check if a double value is greater than zero in C#?

// assuming employeeSalary is a double if(Double. compare(employeeSalary, Double. valueOf(0.0)) > 0 ){ // Employee salary is greater than zero. } else{ // Employee salary is less than or equal to zero. }


2 Answers

You have to set an epsilon that is compatible with the problem you are solving. Then, you could use something like

bool DoubleEquals(double value1, double value2)
{
    return Math.Abs(value1 - value2) < epsilon;
}

EDIT
Since you asked a way to determine if a double is not zero, you could use this function by writing:

if (!DoubleEquals(value, 0)) { /* do your not zero things */ }

I felt this method was better because it's more general purpose.

like image 66
Simone Avatar answered Nov 15 '22 06:11

Simone


Hi depends on what sort of calculations you are doing. Some times you get a very small number which is close to 0 but not quite

I usually do

if (Math.Abs(MyNumber) < 1e-10)

Hope it helps

like image 42
Leon Avatar answered Nov 15 '22 06:11

Leon