Every time I start a new project and when I need to compare some float or double variables I write the code like this one:
if (fabs(prev.min[i] - cur->min[i]) < 0.000001 &&
fabs(prev.max[i] - cur->max[i]) < 0.000001) {
continue;
}
Then I want to get rid of these magic variables 0.000001(and 0.00000000001 for double) and fabs, so I write an inline function and some defines:
#define FLOAT_TOL 0.000001
So I wonder if there is any standard way of doing this? May be some standard header file?
It would be also nice to have float and double limits(min and max values)
From The Floating-Point Guide:
This is a bad way to do it because a
fixed epsilon chosen because it “looks
small” could actually be way too large
when the numbers being compared are
very small as well. The comparison
would return “true” for numbers that
are quite different. And when the
numbers are very large, the epsilon
could end up being smaller than the
smallest rounding error, so that the
comparison always returns “false”.
The problem with the "magic number" here is not that it's hardcoded but that it's "magic": you didn't really have a reason for choosing 0.000001 over 0.000005 or 0.0000000000001, did you? Note that float can approximately represent the latter and still smaller values - it's just about 7 decimals of precision after the first nonzero digit!
If you're going to use a fixed epsilon, you should really choose it according to the requirements of the particular piece of code where you use it. The alternative is to use a relative error margin (see link at the top for details) or, even better, or compare the floats as integers.
The Standard provides an epsilon value. It's in <limits> and you can access the value by std::numeric_limits<float>::epsilon and std::numeric_limits<double>::epsilon. There are other values in there, but I didn't check what exactly is.
You can use std::nextafter for testing two double with the smallest epsilon on a value (or a factor of the smallest epsilon).
bool nearly_equal(double a, double b)
{
return std::nextafter(a, std::numeric_limits<double>::lowest()) <= b
&& std::nextafter(a, std::numeric_limits<double>::max()) >= b;
}
bool nearly_equal(double a, double b, int factor /* a factor of epsilon */)
{
double min_a = a - (a - std::nextafter(a, std::numeric_limits<double>::lowest())) * factor;
double max_a = a + (std::nextafter(a, std::numeric_limits<double>::max()) - a) * factor;
return min_a <= b && max_a >= b;
}
Thanks for your answers, they helped me a lot. I've read these materials:first and second
The answer is to use my own function for relative comparison:
bool areEqualRel(float a, float b, float epsilon) {
return (fabs(a - b) <= epsilon * std::max(fabs(a), fabs(b)));
}
This is the most suitable solution for my needs. However I've wrote some tests and other comparison methods. I hope this will be useful for somebody. areEqualRel passes these tests, others don't.
#include <iostream>
#include <limits>
#include <algorithm>
using std::cout;
using std::max;
bool areEqualAbs(float a, float b, float epsilon) {
return (fabs(a - b) <= epsilon);
}
bool areEqual(float a, float b, float epsilon) {
return (fabs(a - b) <= epsilon * std::max(1.0f, std::max(a, b)));
}
bool areEqualRel(float a, float b, float epsilon) {
return (fabs(a - b) <= epsilon * std::max(fabs(a), fabs(b)));
}
int main(int argc, char *argv[])
{
cout << "minimum: " << FLT_MIN << "\n";
cout << "maximum: " << FLT_MAX << "\n";
cout << "epsilon: " << FLT_EPSILON << "\n";
float a = 0.0000001f;
float b = 0.0000002f;
if (areEqualRel(a, b, FLT_EPSILON)) {
cout << "are equal a: " << a << " b: " << b << "\n";
}
a = 1000001.f;
b = 1000002.f;
if (areEqualRel(a, b, FLT_EPSILON)) {
cout << "are equal a: " << a << " b: " << b << "\n";
}
}
Here is a c++11 implementation of #geotavros 's solution. It makes use of the new std::numeric_limits<T>::epsilon() function and the fact that std::fabs() and std::fmax() now have overloads for float, double and long float.
template<typename T>
static bool AreEqual(T f1, T f2) {
return (std::fabs(f1 - f2) <= std::numeric_limits<T>::epsilon() * std::fmax(std::fabs(f1), std::fabs(f2)));
}
You should use the standard define in float.h:
#define DBL_EPSILON 2.2204460492503131e-016 /* smallest float value such that 1.0+DBL_EPSILON != 1.0 */
or the numeric_limits class:
// excerpt
template<>
class numeric_limits<float> : public _Num_float_base
{
public:
typedef float T;
// return minimum value
static T (min)() throw();
// return smallest effective increment from 1.0
static T epsilon() throw();
// return largest rounding error
static T round_error() throw();
// return minimum denormalized value
static T denorm_min() throw();
};
[EDIT: Made it just a little bit more readable.]
But in addition, it depends on what you're after.
You should be aware that if you are comparing two floats for equality, you
are intrinsically doing the wrong thing. Adding a slop factor to the comparison
is not good enough.
This post has a comprehensive explanation of how to compare floating point numbers:
http://www.altdevblogaday.com/2012/02/22/comparing-floating-point-numbers-2012-edition/
Excerpt:
If you are comparing against zero, then relative epsilons and ULPs based comparisons are usually meaningless. You’ll need to use an
absolute epsilon, whose value might be some small multiple of
FLT_EPSILON and the inputs to your calculation. Maybe.
If you are comparing against a non-zero number then relative epsilons or ULPs based comparisons are probably what you want. You’ll
probably want some small multiple of FLT_EPSILON for your relative
epsilon, or some small number of ULPs. An absolute epsilon could be
used if you knew exactly what number you were comparing against.
Related
In C++, When I calculate 2/3, it will output decimal values, how can I just get the original format (i.e.g 2/3) instead of 0.66666667
Thanks
You can't. You would need to write a class dedicated to holding rational numbers (i.e. fractions). Or maybe just use the Boost Rational Number library.
If I understand correctly, you have a floating point number (a float or double type variable), and you'd like to output this value as a fraction.
If that is the case, you need to further specify your question:
A FP number is a fraction, by definition: A FP number consists of two integers, a mantissa m and an expontent e (and a sign, but that's irrelevant here). So each FP number is really a pair (m,e), and the value f it represents is f=mb^e (where b is a fixed integral base, usually 2). So the natural representation as a fraction is simply m / b^(-e) with e<0 (if e>=0 , f is integral anyway).
However, you probably want to get the fraction with the smallest reasonable divisor. This is a different question. To get is, you could e.g. use the bestappr function from the Pari/GP library. In your case, you'd probably use bestappr(x, A), with x your input, and A the largest denominator you want to try. bestappr will give you the fraction closest to x whose denominator is still smaller than A.
write your own Rational class to calculate divisions
class Rational
{
public:
int numerator, denominator;
Rational(int num, int den=1){
numerator = num;
denominator=den;
}
Rational(Rational other){
numerator = other.numerator;
denominator = other.denominator;
}
double operator / (int divisor){
denominator *= divisor;
simplificate();
return getrealformat();
}
Rational& operator / (int divisor){
denominator *= divisor;
simplificate();
return this;
}
Rational& operator / (Rational &divisor){
numerator *= divisor.numerator;
denominator *= divisor.denominator;
simplificate();
return this;
}
double operator / (int divisor){
denominator *= divisor;
simplificate();
return getrealformat();
}
double getrealformat(){
return numerator/denominator;
}
simplificate(){
int commondivisor = 1;
for(int i=2;i<=min(abs(numerator), abs(denominator));i++)
if( numerator%i == 0 && denominator%i == 0 )
commondivisor = i;
numerator /= commondivisor;
denominator /= commondivisor;
}
};
use
Rational r1(45), r2(90), r3=r1/r2;
cout<<r3.numerator<<'/'<<r3.denominator;
cout<<r3.getrealformat();
how can I just get the original format
(i.e.g 2/3) instead of 0.66666667
Only with great difficulty by wrapping something like the GMP library with custom output operators. Below is a bit more on GMP:
What is GMP?
GMP is a free library for
arbitrary precision arithmetic,
operating on signed integers, rational
numbers, and floating point numbers.
There is no practical limit to the
precision except the ones implied by
the available memory in the machine
GMP runs on. GMP has a rich set of
functions, and the functions have a
regular interface.
The main target applications for GMP
are cryptography applications and
research, Internet security
applications, algebra systems,
computational algebra research, etc.
GMP is carefully designed to be as
fast as possible, both for small
operands and for huge operands. The
speed is achieved by using fullwords
as the basic arithmetic type, by using
fast algorithms, with highly optimised
assembly code for the most common
inner loops for a lot of CPUs, and by
a general emphasis on speed.
GMP is faster than any other bignum
library. The advantage for GMP
increases with the operand sizes for
many operations, since GMP uses
asymptotically faster algorithms.
The first GMP release was made in
1991. It is continually developed and maintained, with a new release about
once a year.
You have to store them in some sort of Fraction class with two integer fields. Of course, you have to simplify the fraction before using it for output.
You can develop your own class or use some libraries, like this one for exact maths: CLN - Class Library for Numbers
This is impossible in general: floating point numbers are not precise and do not retain sufficient information to fully reconstruct a fraction.
You could, however, write a function that heuristically finds an "optimal" approximation, whereby fractions with small numerators and denominators are preferred, as are fractions that have almost the same value as the floating point number.
If you're in full control of the code, Oli's idea is better: don't throw away the information in the first place.
You can store all your fraction's numerators and denominators as intergers. Integers have exact representations in binary.
To simplify efforts, I suggest you stick with known denominators if possible.
I'm working with an application where the fractions are restricted to denominators of powers of 2 or using 3 (for thirds).
I convert to these fractions using an approximation (rounding to the nearest 1.0/24.0).
Without some restrictions, finding the denominator can be quite a chore and take up a lot of the execution time.
I am beginner and this way that I use may not be a proper way
#include <iostream>
using namespace std;
int main ()
{
double a;
double b;
double c;
cout << "first number: ";
cin >> a;
cout << "second number: ";
cin >> b;
c = a/b;
cout << "result is: " << c << endl;
if (b != 0) {
if (a > 0) {
if (c - (int)c > 0 && c - (int)c < 1)
cout << "fraction: " << a << "/" << b;
} else {
if (c - (int)c < 0 && c - (int)c < 1)
cout << "fraction: " << a << "/" << b;
}
}
return 0;
}
Dividing both numbers with their HCF might help.
#include <iostream>
using namespace std;
int main() {
int a,b,q,r;
cin>>a>>b;//first number and second number
q = a/b;
r = a-q*b;
cout<<q<<" "<<r<<" "<<"/"<<" "<<b<<"\n";
return 0;
}
I just got quotient by a/b then got the remainder by a-q*b.
open for suggetions if any.
Use greatest common divisor concept.
if we divide the numbers with gcd of their numbers we get least possible value of those.example:-
#define si long long
int main() {
si int total=4;
si int count=2;
si int g= __gcd(count,total);
count/=g;
total/=g;
cout<<count<<"/"<<total<<endl;
}
for more reference check out this:-https://www.codechef.com/viewsolution/17873537
This is a program to convert a decimal number into a fraction
#include<iostream>
using namespace std;
int main()
{
float num, origNum, rem = 1;
int den = 1, i, count=0, gcd=1;
cout << "Enter any float number to convert it into mixed fraction: ";
cin >> origNum;
num = origNum - static_cast<int>(origNum);
if (num > 0.1)
{
while ( (rem > 0.1) )
{
num = num * 10;
rem = num - static_cast<int>(num);
count++;
}
for (i = 1; i <= count; i++) // counter is for the calculation of denominator part of mixed fraction
{
den = den * 10;
}
for (i = 2; i <= num|| i<=rem; i++)
{
if( (static_cast<int>(num) % i == 0) && (den % i == 0) )
{
gcd = i;
}
}
cout << (static_cast<int>(origNum)) << " and " << (static_cast<int>(num))/gcd << "/" << den/gcd;
}
else
cout << (static_cast<int>(origNum));
return 0;
}
Background
I want to write an is_even( decimal::decimal64 d ) function that returns true if the least-significant digit is even.
Unfortunately, I can't seem to find any methods to extract the coefficient from a decimal64.
Code
#include <iostream>
#include <decimal/decimal>
using namespace std;
static bool is_even( decimal::decimal64 d )
{
return true; // fix this - want to: return coefficient(d)%2==0;
}
int main()
{
auto d1 = decimal::make_decimal64( 60817ull, -4 ); // not even
auto d2 = decimal::make_decimal64( 60816ull, -4 ); // is even
cout << decimal64_to_float( d1 ) << " " << is_even( d1 ) << endl;
cout << decimal64_to_float( d2 ) << " " << is_even( d2 ) << endl;
return 0;
}
It's a little odd that there's no provided function to recover the coefficient of a decimal; but you can just multiply by 10 raised to its negative exponent:
bool is_even(decimal::decimal64 d)
{
auto q = quantexpd64(d);
auto coeff = static_cast<long long>(d * decimal::make_decimal64(1, -q));
return coeff % 2 == 0;
}
assert(!is_even(decimal::make_decimal64(60817ull, -4)));
assert(!is_even(decimal::make_decimal64(60816ull, -4)));
I would use corresponding fmod function if possible.
static bool is_even( decimal::decimal64 d )
{
auto e = quantexpd64(d);
auto divisor = decimal::make_decimal64(2, e);
return decimal::fmodd64(d, divisor) == decimal::make_decimal64(0,0);
}
It constructs a divisor that is 2*10^e where e is exponent of the tested value. Then it performs fmod and checks whether it is equal to a decimal 0. (NOTE: operator== for decimal is said to be IEEE 754-2008 conformant so we don't need to take care of -0.0).
An alternative would be to multiply the number by 10^-e (to "normalize" it) and cast it to an integer type and traditionally check modulo. I think this is #ecatmur's proposal. Though the "normalization" might fail if it goes out of chosen integer type bounds.
I think fmod is better when it comes to overflows. You are guaranteed to hold 2*10^e given that is a proper d decimal (i.e. not a NaN, or an inf).
One caveat I see is the definition of least significant digit. The above methods assume that least significant digit is denoted by e, which sometimes might be counterintuitive. I.e. is decimal(21,2) even? Then is decimal(2100,0)?
I am at the moment trying to code a titration curve simulator. But I am running into some trouble with comparing two values.
I have created a small working example that perfectly replicates the bug that I encounter:
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
double a, b;
a = 5;
b = 0;
for(double i = 0; i<=(2*a); i+=0.1){
b = i;
cout << "a=" << a << "; b="<<b;
if(a==b)
cout << "Equal!" << endl;
else
cout << endl;
}
return 0;
}
The output at the relevant section is
a=5; b=5
However, if I change the iteration increment from i+=0.1 to i+=1 or i+=0.5 I get an output of
a=5; b=5Equal!
as you would expect.
I am compiling with g++ on linux using no further flags and I am frankly at a loss how to solve this problem. Any pointers (or even a full-blown solution to my problem) are very appreciated.
Unlike integers, multiplying floats/doubles and adding them up doesn't produce exactly the same results.
So the best practice is find if the abs of their difference is small enough.
If you have some idea on the size of the numbers, you can use a constant:
if (fabs(a - b) < EPS) // equal
If you don't (much slower!):
float a1 = fabs(a), b1 = fabs(b);
float mn = min(a1,b1), mx = max(a1,b1);
if (mn / mx > (1- EPS)) // equal
Note:
In your code, you can use std::abs instead. Same for std::min/max. The code is clearer/shorter when using the C functions.
I would recommend restructuring your loop to iterate using integers and then converting the integers into doubles, like this:
double step = 0.1;
for(int i = 0; i*step<=2*a; ++i){
b = i*step;
cout << "a=" << a << "; b="<<b;
if(a==b)
cout << "Equal!" << endl;
else
cout << endl;
}
This still isn't perfect. You possibly have some loss of precision in the multiplication; however, the floating point errors don't accumulate like they do when iterating using floating point values.
Floating point arithmetic is... interesting. Testing equality is annoying with floats/doubles in most languages because it is impossible to accurately represent many numbers in IEEE floating point math. Basically, where you might compute an expression to be 5.0, the compiler might compute it to be 4.9999999, because it's the closest representable number in the IEEE standard.
Because these numbers are slightly different, you end up with an inequality. Because it's unmaintainble to try and predict which number you will see at compile time, you can't/shouldn't attempt to hard code either one of them into your source to test equality with. As a hard rule, avoid directly checking equality of floating point numbers.
Instead, test that they are extremely close to being equal with something like the following:
template<typename T>
bool floatEqual(const T& a, const T& b) {
auto delta = a * 0.03;
auto minAccepted = a - delta;
auto maxAccepted = a + delta;
return b > minAccepted && b < maxAccepted;
}
This checks whether b is within a range of + or - 3% of the value of a.
So suppose we have a float type XType in which we have two numbers:
XType const a = 1.2345
XType const b = 1.2300
Then I want a function IsClose(XType const f1,XType const f2,unsigned const truncated_figures) such that
// the numbers are equal if the last two figures are ignored (1.23 == 1.23)
IsClose<XType>(a,b,2) == true
// the numbers are not equal if only the last is ignored (1.234 != 1.230)
IsClose<XType>(a,b,1) == false
So far I have this ugly mess, but I'm yet to convince myself it's correct:
// check if two floating point numbers are close to within "figures_tolerance" figures of precision for the applicable type
template <typename FloatType>
bool const IsClose(FloatType const f1, FloatType const f2, unsigned const figures_tolerance)
{
FloatType const tolerance_exponent = std::pow(10.0,figures_tolerance);
FloatType const tolerance =
std::pow(tolerance_exponent,std::log10(f1)) *
std::numeric_limits<FloatType>::epsilon()
;
return std::abs(f1 - f2) < tolerance;
}
My reasoning is that the tolerance should be the epsilon raised to the order of magnitude that the number exceeds or subseeds 1.0 (the significant figures for which the epsilon is based). Does this make sense? Is there a better, more reliable way?
EDIT: My solution using the template function is below (it is based on user763305's answer below)
// check if two floating point numbers are within the last n digits of precision for the
// largest of the two numbers being compared.
template <typename FloatType>
bool const IsWithinPrecision(FloatType const f1, FloatType const f2, unsigned const n = 1U)
{
FloatType const f_ref = std::max(std::abs(f1), std::abs(f2));
FloatType const distance = std::abs(f1 - f2);
FloatType const e = std::numeric_limits<FloatType>::epsilon();
return distance < std::pow((FloatType) 10.0, (FloatType) n) * e * f_ref;
}
To test whether two numbers are within n significant digits of each other, use the inequality
abs(a - b) < pow(0.1, n) * max(abs(a), abs(b))
However, I usually find it more useful to test if the number of significant digits is at least the maximum possible number of significant digits (given the precision of the floating point type) minus n. This can be done using the inequality
abs(a - b) < pow(10.0, n) * std::numeric_limits<...>::epsilon() * max(abs(a), abs(b))
In other words, n is the number of significant digits we have lost through rounding errors. Something like n = 2 or 3 usually works in practice.
The reason this works is that the distances between a floating point number a and the next representable floating point numbers below and above a lie between
0.5 * std::numeric_limits<...>::epsilon() * abs(a)
and
std::numeric_limits<...>::epsilon() * abs(a)
Also, the above inequality does not work if you are dealing with very small, or more precisely, denormal numbers. Then you should instead use the inequality
abs(a - b) < pow(10.0, n) * max(
std::numeric_limits<...>::epsilon() * max(abs(a), abs(b)),
std::numeric_limits<...>::denorm_min()
)
Since this is just for debugging, it may be possible to be lax and use a simple test for relative error, such as:
if (fabs(f1 - f2) <= SomeNumber * fabs(f2)) ThingsAreGood else ThingsAreBad;
This supposes that f2 is the known good (or at least known-to-be-better) value and that the error from rounding in floating-point operations is proportional to f2. Note that computations can produce errors in complicated ways. For example, if various other values were added to and subtracted from f1 along the way, so that intermediate values had much larger magnitudes than the final result represented by f2, then the rounding errors may be proportional to those large intermediate values rather than to f2. In this case, you may need to compute an error threshold based on the intermediate calculations rather than on f2.
Taking care of the situation pointed out by Eric Postpischil as well, This function tells whether the 2 numbers are close enough or not according to the precision.
bool const IsClose(FloatType const f1, FloatType const f2, unsigned const figures_tolerance)
{
FloatType res = f1-f2;
res = res*pow(10.0,figures_tolerance);
return !bool(int(res));
}
The solution used in the edit answer did not work in my case for large number comparison.
I wrote a function using string comparison with a given digit precision
#include <iomanip>
/**
* Compare two number with a given digit precision
*
* #tparam T - Number precision
*
* #param n1 - First number to compare
* #param n2 - Second number to compare
* #param n - The first n digits that must be equals between the two numbers
*
* #return True if the n first digits of the two numbers are equals, false otherwise
*/
template<typename T>
bool isEqual(T n1, T n2, int n)
{
int index = 0;
std::ostringstream a, b;
a << std::setprecision(n);
b << std::setprecision(n);
std::cout << std::setprecision(n);
a << std::fixed;
b << std::fixed;
std::cout << std::fixed;
a << n1;
b << n2;
while (a.str()[index] == b.str()[index] && index < n) {
index++;
}
if (index != n) {
std::cout << "n1 != n2\n\nn1 = " << a.str() << "\nn2 = " << b.str() << "\ndiffer at index " << index << std::endl;
}
return index == n;
}
I've searched all over the net, but I could not find a solution to my problem. I simply want a function that rounds double values like MS Excel does. Here is my code:
#include <iostream>
#include "math.h"
using namespace std;
double Round(double value, int precision) {
return floor(((value * pow(10.0, precision)) + 0.5)) / pow(10.0, precision);
}
int main(int argc, char *argv[]) {
/* The way MS Excel does it:
1.27815 1.27840 -> 1.27828
1.27813 1.27840 -> 1.27827
1.27819 1.27843 -> 1.27831
1.27999 1.28024 -> 1.28012
1.27839 1.27866 -> 1.27853
*/
cout << Round((1.27815 + 1.27840)/2, 5) << "\n"; // *
cout << Round((1.27813 + 1.27840)/2, 5) << "\n";
cout << Round((1.27819 + 1.27843)/2, 5) << "\n";
cout << Round((1.27999 + 1.28024)/2, 5) << "\n"; // *
cout << Round((1.27839 + 1.27866)/2, 5) << "\n"; // *
if(Round((1.27815 + 1.27840)/2, 5) == 1.27828) {
cout << "Hurray...\n";
}
system("PAUSE");
return EXIT_SUCCESS;
}
I have found the function here at stackoverflow, the answer states that it works like the built-in excel rounding routine, but it does not. Could you tell me what I'm missing?
In a sense what you are asking for is not possible:
Floating point values on most common platforms do not have a notion of a "number of decimal places". Numbers like 2.3 or 8.71 simply cannot be represented precisely. Therefore, it makes no sense to ask for any function that will return a floating point value with a given number of non-zero decimal places -- such numbers simply do not exist.
The only thing you can do with floating point types is to compute the nearest representable approximation, and then print the result with the desired precision, which will give you the textual form of the number that you desire. To compute the representation, you can do this:
double round(double x, int n)
{
int e;
double d;
std::frexp(x, &e);
if (e >= 0) return x; // number is an integer, nothing to do
double const f = std::pow(10.0, n);
std::modf(x * f, &d); // d == integral part of 10^n * x
return d / f;
}
(You can also use modf instead of frexp to determine whether x is already an integer. You should also check that n is non-negative, or otherwise define semantics for negative "precision".)
Alternatively to using floating point types, you could perform fixed point arithmetic. That is, you store everything as integers, but you treat them as units of, say, 1/1000. Then you could print such a number as follows:
std::cout << n / 1000 << "." << n % 1000;
Addition works as expected, though you have to write your own multiplication function.
To compare double values, you must specify a range of comparison, where the result could be considered "safe". You could use a macro for that.
Here is one example of what you could use:
#define COMPARE( A, B, PRECISION ) ( ( A >= B - PRECISION ) && ( A <= B + PRECISION ) )
int main()
{
double a = 12.34567;
bool equal = COMPARE( a, 12.34567F, 0.0002 );
equal = COMPARE( a, 15.34567F, 0.0002 );
return 0;
}
Thank you all for your answers! After considering the possible solutions I changed the original Round() function in my code to adding 0.6 instead of 0.5 to the value.
The value "127827.5" (I do understand that this is not an exact representation!) becomes "127828.1" and finally through floor() and dividing it becomes "1.27828" (or something more like 1.2782800..001). Using COMPARE suggested by Renan Greinert with a correctly chosen precision I can safely compare the values now.
Here is the final version:
#include <iostream>
#include "math.h"
#define COMPARE(A, B, PRECISION) ((A >= B-PRECISION) && (A <= B+PRECISION))
using namespace std;
double Round(double value, int precision) {
return floor(value * pow(10.0, precision) + 0.6) / pow(10.0, precision);
}
int main(int argc, char *argv[]) {
/* The way MS Excel does it:
1.27815 1.27840 // 1.27828
1.27813 1.27840 -> 1.27827
1.27819 1.27843 -> 1.27831
1.27999 1.28024 -> 1.28012
1.27839 1.27866 -> 1.27853
*/
cout << Round((1.27815 + 1.27840)/2, 5) << "\n";
cout << Round((1.27813 + 1.27840)/2, 5) << "\n";
cout << Round((1.27819 + 1.27843)/2, 5) << "\n";
cout << Round((1.27999 + 1.28024)/2, 5) << "\n";
cout << Round((1.27839 + 1.27866)/2, 5) << "\n";
//Comparing the rounded value against a fixed one
if(COMPARE(Round((1.27815 + 1.27840)/2, 5), 1.27828, 0.000001)) {
cout << "Hurray!\n";
}
//Comparing two rounded values
if(COMPARE(Round((1.27815 + 1.27840)/2, 5), Round((1.27814 + 1.27841)/2, 5), 0.000001)) {
cout << "Hurray!\n";
}
system("PAUSE");
return EXIT_SUCCESS;
}
I've tested it by rounding a hundred double values and than comparing the results to what Excel gives. They were all the same.
I'm afraid the answer is that Round cannot perform magic.
Since 1.27828 is not exactly representable as a double, you cannot compare some double with 1.27828 and hope it will match.
You need to do the maths without the decimal part, to get that numbers... so something like this.
double dPow = pow(10.0, 5.0);
double a = 1.27815;
double b = 1.27840;
double a2 = 1.27815 * dPow;
double b2 = 1.27840 * dPow;
double c = (a2 + b2) / 2 + 0.5;
Using your function...
double c = (Round(a) + Round(b)) / 2 + 0.5;