
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Floating point comparison in C++
Here we will see how to compare two floating point data using C++. The floating point comparison is not similar to the integer comparison.
To compare two floating point values, we have to consider the precision in to the comparison. For example, if two numbers are 3.1428 and 3.1415, then they are same up to the precision 0.01, but after that, like 0.001 they are not same.
To compare using this criteria, we will find the absolute value after subtracting one floating point number from another, then check whether the result is lesser than the precision value or not. By this we can decide that they are equivalent or not.
Example
#include <iostream> #include <cmath> using namespace std; bool compare_float(float x, float y, float epsilon = 0.01f){ if(fabs(x - y) < epsilon) return true; //they are same return false; //they are not same } int main() { float x, y; x = 22.0f/7.0f; y = 3.1415f; if(compare_float(x, y)){ cout << "They are equivalent" << endl; } else { cout << "They are not equivalent" << endl; } if(compare_float(x, y, 0.001f)){ cout << "They are equivalent" << endl; } else { cout << "They are not equivalent" << endl; } }
Output
They are equivalent They are not equivalent
- Related Questions & Answers
- Comparison of floating point values in PHP.
- C++ Floating Point Manipulation
- What are C++ Floating-Point Constants?
- What are floating point literals in C#?
- Signed floating point numbers
- Floating-point hexadecimal in Java
- Fixed Point and Floating Point Number Representations
- Integer literals vs Floating point literals in C#
- PHP Floating Point Data Type
- Decimal fixed point and floating point arithmetic in Python
- Floating-point conversion characters in Java
- Format floating point number in Java
- C Program to Multiply two Floating Point Numbers?
- Floating Point Operations and Associativity in C, C++ and Java
- Convert a floating point number to string in C
Advertisements