- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to compare float and double in C++?
Comparing floats and double variables depends on what your end goal is. If you want a runnable function without going too much in details and won't have a problem in some inaccurate calculations you can use the following function −
Example
#include<iostream> using namespace std; // Define the error that you can tolerate #define EPSILON 0.000001 bool areSame(double a, double b) { return fabs(a - b) < EPSILON; } int main() { double a = 1.005; double b = 1.006; cout << areSame(a, a); cout << areSame(a, b); }
output
This will give the output −
1 0
This function takes your tolerance for error and checks if the threshold is greater than the difference between the numbers you're comparing. If you need something much more accurate, you're better off reading this excellent blog post:https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/
Advertisements