Problem in comparing Floating point numbers and how to compare them correctly?
Last Updated :
03 May, 2023
In this article, we will see what is the problem in comparing floating-point numbers and we will discuss the correct way to compare two floating-point numbers.
What is the problem in comparing Floating-Point Numbers usually?
Let us first compare two floating-point numbers with the help of relational operator (==).
Example: Using "==" for comparison
CPP
// C++ program to compare
// floating point numbers
#include <bits/stdc++.h>
using namespace std;
void compareFloatNum(double a, double b)
{
if (a == b) {
cout << "The numbers are equal"
<< endl;
}
else {
cout << "The numbers are not equal"
<< endl;
}
}
// Driver code
int main()
{
double a = (0.3 * 3) + 0.1;
double b = 1;
compareFloatNum(a, b);
}
Java
// Java program to compare
// floating point numbers
class GFG
{
static void compareFloatNum(double a, double b)
{
if (a == b)
{
System.out.print("The numbers are equal" + "\n");
}
else
{
System.out.print("The numbers are not equal" + "\n");
}
}
// Driver code
public static void main(String[] args)
{
double a = (0.3 * 3) + 0.1;
double b = 1;
compareFloatNum(a, b);
}
}
// This code is contributed by 29AjayKumar
Python
# Python program to compare
# floating point numbers
def compareFloatNum(a, b):
if (a == b):
print("The numbers are equal")
else:
print("The numbers are not equal")
# Driver code
a = (0.3 * 3) + 0.1
b = 1
compareFloatNum(a, b)
# This code is contributed by mohit kumar 29
C#
// C# program to compare
// floating point numbers
using System;
class GFG
{
static void comparefloatNum(double a, double b)
{
if (a == b)
{
Console.Write("The numbers are equal" + "\n");
}
else
{
Console.Write("The numbers are not equal" + "\n");
}
}
// Driver code
public static void Main(String[] args)
{
double a = (0.3 * 3) + 0.1;
double b = 1;
comparefloatNum(a, b);
}
}
// This code is contributed by PrinciRaj1992
JavaScript
<script>
function compareFloatNum(a,b)
{
if (a == b)
{
document.write("The numbers are equal" + "<br>");
}
else
{
document.write("The numbers are not equal" + "<br>");
}
}
let a = (0.3 * 3) + 0.1;
let b = 1;
compareFloatNum(a, b);
// This code is contributed by patel2127
</script>
Output: The numbers are not equal
Time complexity of this program is O(1), as it only performs a comparison between two floating point numbers.
The space complexity is also O(1), as the program uses only a constant amount of memory for storing the two floating point numbers and a few local variables used for the comparison.
Why does this problem occur?
In the case of floating-point numbers, the relational operator (==) does not produce correct output, this is due to the internal precision errors in rounding up floating-point numbers.
In the above example, we can see the inaccuracy in comparing two floating-point numbers using "==" operator. The two numbers 'a' and 'b' are equal ( as (0.3 * 3) + 0.1 = 1 ) but the program results in an incorrect output.
Let's take a closer look at the numbers in the next snippet.
CPP
// C++ program to compare
// floating point numbers
#include <bits/stdc++.h>
using namespace std;
void printFloatNum(double a, double b)
{
// To print decimal numbers up to 20 digits
cout << setprecision(20);
cout << "a is : " << a << endl;
cout << "b is : " << b << endl;
}
// Driver code
int main()
{
double a = (0.3 * 3) + 0.1;
double b = 1;
printFloatNum(a, b);
}
Python3
# Python 3 program to compare
# floating point numbers
def printFloatNum(a, b):
# To print decimal numbers up to 20 digits
print("a is : %.20f" %a)
print("b is : %.20f" %b)
# Driver code
if __name__ == "__main__":
a = (0.3 * 3) + 0.1
b = 1
printFloatNum(a, b)
# This code is contributed by ukasp.
JavaScript
// JavaScript program to compare floating point numbers
function printFloatNum(a, b) {
// To print decimal numbers up to 20 digits
console.log(`a is : ${a.toFixed(20)}`);
console.log(`b is : ${b.toFixed(20)}`);
}
// Driver code
let a = (0.3 * 3) + 0.1;
let b = 1;
printFloatNum(a, b);
Java
import java.util.*;
public class CompareFloatingPointNumbers {
public static void printFloatNum(double a, double b) {
// To print decimal numbers up to 20 digits
System.out.println(String.format("a is : %.20f", a));
System.out.println(String.format("b is : %.20f", b));
}
public static void main(String[] args) {
double a = (0.3 * 3) + 0.1;
double b = 1;
printFloatNum(a, b);
}
}
Output: a is : 0.99999999999999988898
b is : 1
Time complexity:
The program has a constant time complexity, as it only performs a fixed set of operations and does not depend on the input size. Therefore, the time complexity is O(1).
Space complexity:
The program uses a fixed amount of memory for the double variables a and b, as well as for the output printed to the console. Therefore, the space complexity is also O(1).
Now we can see the internal rounding error in floating-point numbers. Number 'a' is not correctly rounded up to 1,
there is an internal error in rounding up, a very small error but makes a huge difference when we are comparing the numbers.
How to compare floating-point numbers correctly?
If we do have to compare two floating-point numbers then rather than using "==" operator we will find the absolute difference between the numbers (which if were correctly represented, the difference would have been 0) and compare it with a very small number 1e-9 (i.e 10^-9, this number is very small) and if the difference is less than this number, we can safely say that the two floating-point numbers are equal.
Example:
C++
// C++ program to compare
// floating point numbers correctly
#include <bits/stdc++.h>
using namespace std;
void compareFloatNum(double a, double b)
{
// Correct method to compare
// floating-point numbers
if (abs(a - b) < 1e-9) {
cout << "The numbers are equal "
<< endl;
}
else {
cout << "The numbers are not equal "
<< endl;
}
}
// Driver code
int main()
{
double a = (0.3 * 3) + 0.1;
double b = 1;
compareFloatNum(a, b);
}
Java
// Java program to compare
// floating point numbers correctly
class GFG
{
static void compareFloatNum(double a, double b)
{
// Correct method to compare
// floating-point numbers
if (Math.abs(a - b) < 1e-9)
{
System.out.print("The numbers are equal "
+"\n");
}
else
{
System.out.print("The numbers are not equal "
+"\n");
}
}
// Driver code
public static void main(String[] args)
{
double a = (0.3 * 3) + 0.1;
double b = 1;
compareFloatNum(a, b);
}
}
// This code is contributed by Rajput-Ji
Python3
# Python program to compare
# floating point numbers correctly
def compareFloatNum(a, b):
# Correct method to compare
# floating-point numbers
if (abs(a - b) < 1e-9):
print("The numbers are equal ");
else:
print("The numbers are not equal ");
# Driver code
if __name__ == '__main__':
a = (0.3 * 3) + 0.1;
b = 1;
compareFloatNum(a, b);
# This code is contributed by PrinciRaj1992
C#
// C# program to compare
// floating point numbers correctly
using System;
class GFG
{
static void comparefloatNum(double a, double b)
{
// Correct method to compare
// floating-point numbers
if (Math.Abs(a - b) < 1e-9)
{
Console.Write("The numbers are equal "
+"\n");
}
else
{
Console.Write("The numbers are not equal "
+"\n");
}
}
// Driver code
public static void Main(String[] args)
{
double a = (0.3 * 3) + 0.1;
double b = 1;
comparefloatNum(a, b);
}
}
// This code is contributed by 29AjayKumar
JavaScript
<script>
// Javascript program to compare
// floating point numbers correctly
function compareFloatNum(a,b)
{
// Correct method to compare
// floating-point numbers
if (Math.abs(a - b) < 1e-9)
{
document.write("The numbers are equal "
+"<br>");
}
else
{
document.write("The numbers are not equal "
+"<br>");
}
}
// Driver code
let a = (0.3 * 3) + 0.1;
let b = 1;
compareFloatNum(a, b);
// This code is contributed by unknown2108
</script>
Output: The numbers are equal
This code results in the correct output, so whenever two floating point numbers are two be compared then rather than using "==" operator, we will use the above technique.
Similar Reads
Rounding Floating Point Number To two Decimal Places in C and C++
How to round off a floating point value to two places. For example, 5.567 should become 5.57 and 5.534 should become 5.53 First Method:- Using Float precision C++ #include<bits/stdc++.h> using namespace std; int main() { float var = 37.66666; // Directly print the number with .2f precision cou
2 min read
Convert a floating point number to string in C
Write a C function ftoa() that converts a given floating-point number or a double to a string. Use of standard library functions for direct conversion is not allowed. The following is prototype of ftoa(). The article provides insight of conversion of C double to string. ftoa(n, res, afterpoint) n --
3 min read
Precision of Floating Point Numbers in C++ (floor(), ceil(), trunc(), round() and setprecision())
The decimal equivalent of 1/3 is 0.33333333333333â¦. An infinite length number would require infinite memory to store, and we typically have 4 or 8 bytes. Therefore, Floating point numbers store only a certain number of significant digits, and the rest are lost. The precision of a floating-point numb
4 min read
How to check whether a number is in the range[low, high] using one comparison ?
This is simple, but interesting programming puzzle. Given three integers, low, high and x such that high >= low. How to check if x lies in range [low, high] or not using single comparison. For example, if range is [10, 100] and number is 30, then output is true and if the number is 5, then output
3 min read
Write a one line C function to round floating point numbers
Algorithm: roundNo(num) 1. If num is positive then add 0.5. 2. Else subtract 0.5. 3. Type cast the result to int and return. Example: num = 1.67, (int) num + 0.5 = (int)2.17 = 2 num = -1.67, (int) num - 0.5 = -(int)2.17 = -2 Implementation: c /* Program for rounding floating point numbers */ # inclu
1 min read
Check whether the given floating point number is a palindrome
Given a floating-point number N, the task is to check whether it is palindrome or not. Input: N = 123.321 Output: YesInput: N = 122.1 Output: No Approach: First, convert the given floating-point number into a character array.Initialize the low to first index and high to the last index.While low <
4 min read
Comparison of double and float primitive types in Java
Consider the following two codes in Java: Java // This program prints true class Geeksforgeeks { public static void main(String args[]) { float f = 5.25f; double d = 5.25 System.out.println(f == d); } } Output true Java // But this program prints false. class Geeksforgeeks { public static void main(
2 min read
Check whether the number formed by concatenating two numbers is a perfect square or not
Given two numbers a and b and the task is to check whether the concatenation of a and b is a perfect square or not.Examples: Input: a = 1, b = 21 Output: Yes 121 = 11 Ã 11, is a perfect square. Input: a = 100, b = 100 Output: No 100100 is not a perfect square. Approach: Initialize the number as stri
4 min read
Comparison of a float with a value in C
Predict the output of the following C program. C #include<stdio.h> int main() { float x = 0.1; if (x == 0.1) printf("IF"); else if (x == 0.1f) printf("ELSE IF"); else printf("ELSE"); } The output of above program is "ELSE IF" which means the expression "x == 0.1"
4 min read
Assigning an integer to float and comparison in C/C++
Consider the below C++ program and predict the output. CPP #include <iostream> using namespace std; int main() { float f = 0xffffffff; unsigned int x = 0xffffffff; // Value 4294967295 if (f == x) cout << "true"; else cout << "false"; return 0; } The output of ab
2 min read