Jump to content

8 posts in this topic

Recommended Posts

Posted

Given two double values double1 , double2, why isn’t it reliable to test their equality using:

double1 == double2;

???

Comment possible code below!!

If you are the first person to get this I will follow you!!

 

HINT:

Spoiler

If both doubles are assigned NaN  (not a number) it returns false! 

How could you COMPARE the two values against a real number (zero)

 

Posted (edited)
1 hour ago, LifeElevated said:

How could you COMPARE the two values against a real number (zero)

Can you specify it?... I dont understand

is it this?

Double.compare(double1,double2) == 0);

Updated by FinnLord
Posted
18 hours ago, FinnLord said:

Can you specify it?... I dont understand

is it this?

Double.compare(double1,double2) == 0);

Yes this is the right answer. Now tell us why (==) isn't efficient to compare double variables?

Posted
On 5/18/2018 at 12:21 AM, LifeElevated said:

Honestly this is worded to weird ?

Its not. I joined this club so i could respond

 

If you have a double or a float in any language, you can't expect them to be completely precise. For example, if you have two doubles 

double num1 = 3.0;
double num2 = 3.0;

It looks like they should be equal, right? But they most likely aren't. why? because  floats and doubles are very precise. Here's what num1 and num2 really are:

num1: 3.00000000000000000000000000000000382918
num2: 3.00000000000000000000000000000000261527

So that's why you can't compare doubles and floats with the == operator in any language really. Here's some code to correctly compare floats in c++

bool cmpf(float a, float b){
	return (fabs(a - b) < 0.005f);
}

I guess in Java it would be something ridiculous like

static boolean cmpf(double a, double b){
	return (Math.abs(a - b) < 0.005);
}

I f***ing hate java

×
  • Create New...

Important Information

We would like to place cookies on your device to help make this website better. The website cannot give you the best user experience without cookies. You can accept or decline our cookies. You may also adjust your cookie settings. Privacy Policy - Guidelines