I am working through a beginning C++ class and my book(Starting Out with C++ Early Objects 7th edition) has a very poor example of how to check the value of a floating point variable.

The book example in question(filename pr4-04.cpp):

```
// This program demonstrates how to safely test a floating-point number
// to see if it is, for all practical purposes, equal to some value.
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
double result = .666667 * 6.0;
// 2/3 of 6 should be 4 and, if you print result, 4 is displayed.
cout << "result = " << result << endl;
// However, internally result is NOT precisely equal to 4.
// So test to see if it is "close" to 4.
if (abs(result - 4.0 < .0001))
cout << "result DOES equal 4!" << endl;
else
cout << "result DOES NOT equal 4!" << endl;
return 0;
}
```

And I use g++ in Ubuntu to compile my code like this:

```
g++ pr4-04.cpp -o pr4-04 && ./pr4-04
```

And I get this error:

```
error: call of overloaded ‘abs(bool)’ is ambiguous
```

I am able to fix this by changing abs() to fabs(), but this is still super confusing! Why is the book giving us things which won't compile, or is this just me? Why does the cout of 'result' give 4 instead of 4.000002? Why does this value seem to change when it is used in the if{} statement?

I get that we can't just use == to check for equivalence, but why do I need to use the absolute value? I get the same answer whether or not I use it. So what is the point?

Not to mention, this seems like a very poor way to check for floating point equivalence. Is there a better way to do this? This topic seems awfully important.

I found this topic here on stackoverflow, but their solution:

```
fabs(f1 - f2) < precision-requirement
fabs(f1 - f2) < max(fabs(f1), fabs(f2)) * percentage-precision-requirement
```

Doesn't make much sense to me in the context of my 4 chapters worth of C++ experience. I would greatly appreciate some help. Our book has given me a whopping 6 sentences of text to explain all of this.

Edit: As suggested by some I tried to find an errata page, but after 30mins of searching the textbook, internet, and my course website I was only able to find this downloadable zip file, which required a login -_-

I also copied the code perfectly. That was not **MY** typo, I copied it directly from a CD with the code on it. It is also typed that way in the book.

```
if (abs(result - 4.0 < .0001))
```

The parenthesis are wrong, you probably mean: `if (abs(result-4.0) < .0001)`

.

As to why it did not compile, the standard determines in §26.8p8 that

In addition to the double versions of the math functions in , C++ adds float and long double overloaded versions of these functions, with the same semantics.

The expression `(result-4.0 < .0001)`

yields a `bool`

, and there is no overload of `abs`

that takes a `bool`

argument, but there are multiple versions of `abs`

for which the argument is implicitly convertible from `bool`

. The compiler does not find one of the conversion sequences better than the rest and bails out with the ambiguity error.

The problem is clearly the line

```
if (abs(result - 4.0 < .0001))
```

which should be written as

```
if (abs(result - 4.0) < .0001)
```

I would assume that this is a simple typo. Report the error to the author of the book!

BTW, the original code does compile on my system without any problem, giving the expected result! That is, even if the author tested the code he may not have noticed that it is problematic!

Also answering the question on why `abs()`

is needed: some decimal numbers are rounded to a floating point value which is slightly smaller than the expected result while others are rounded to number which are slightly bigger. In which direction the values are round (if at all: some decimal numbers can be represented exactly using binary floating points) is somewhat hard to predict. Thus, the `result`

may be slightly bigger or slightly smaller than the expectation and the difference, thus, positive or negative, respectively.

Similar Questions

How do you provoke a floating point error in 32 bits (commonly known as coprocessor error [INT 16 :8086].

I am trying to convert a floating point number to string. I know you can do it using ostringstream & sprintf etc. but in the project I am working I am trying to do it using my own functions only (

Possible Duplicate: Why is floating point arithmetic in C# imprecise? Why is there a bias in floating point ops? Any specific reason? Output: 160 139 static void Main() { float x = (float) 1.6; int

This question already has an answer here: Why is volatile needed in c? 13 answers Question about the volatile keyword 5 answers I'm currently learning C in class and I'm having some confusi

I am a beginner, and i am working on a C++ program that simlifies fractions, however I am getting this weird statement printed, it does not indicate an error, but it gives me the output Floating poin

I am reading a C book, talking about ranges of floating point, the author gave the table: I dont know where the numbers in the columns Smallest Positive and Largest Value come from.

I had to debug some code that was exhibiting transient and sporadic behavior, which ultimately could be attributed to an uninitialized float in a line of initializations, i.e.: float a = number, b, c

So I want to verify the hexadecimal representation of the number 1.0 in Language C, below are my codes: int main(int argc, char **argv) { void showBytes(unsigned char * p,int size){ int i; for (i=0;i&

#define AND=&&; public static final String AND = &&; //GIVES ERROR i want to define the operators as normal variables names in my code same like we do in C language using #define, how

Why isn't 0f treated as a floating point literal in C++? #include <iostream> using namespace std; int main(){ cout << 0f << endl; return 0; } Compiling the above gives me C2509 (s

The Intel Advanced Vector Extensions (AVX) offers no dot product in 256-bit version (ymm register) for double precision floating point variables. The Why? question have been very briefly treated in

Today I was tracking down why my program was getting some unexpected checksum-mismatch errors, in some code that I wrote that serializes and deserializes IEEE-754 floating-point values, in a format th

I am having trouble trying to understand how logical operators work in C. I already understand how the bit-level operators work, and I also know that logical operators treat nonzero arguments as repre

I've encountered a strange error trying to work with a floating point number. I'm attempting to calculate the log10 (in math.h) of the following number: -0.000000000000000000000000000000002584877722

I am working on block compressed sparse row format of sparse matrix. I need to convert a nonzero element into 64 bit floating point. I need a syntax in c OR C++ for that?

I was searching couple of forums to get some ideas on how to serialize floating point numbers and I happen to come across the following code. oxdrstream& oxdrstream::operator<<( float source

This question is similar to questions that have been asked regarding floating-point error in other languages (for example here), however I haven't found a satisfactory solution. I'm working on a proj

myInt = int( 5 * myRandom() ) myRandom() is a randomly generated float, which should be 0.2. So this statement should evaluate to be 1. My question: is it possible that due to a floating point error

I am struggling to get a reliable way to catch floating points exceptions under Visual Studio (2005 or 2008). By default, under visual studio, floating point exceptions are not caught, and they are qu

I found a problem with host - client float standard in OpenCL. The problem was that the floating points calculated by Opencl is not in the same floating point limits as my visual studio 2010 compiler,

I'm running the program and I'm trying to make it print out the floating point. I've tried putting %f, and it gave me the same number but with 0 at the end. And in my function definition I tried to ma

Possible Duplicate: Manipulating and comparing floating points in java Am I supposed to use an Epsilon while comparing floating point numbers in Java ? Does the Float.compare(float f1, float f2) sta

I was wondering if anybody has a good implementation of floating point/ double comparison for CUDA. I'd like to use something (semi) standard, instead of writing my own. I couldn't find something stan

Does anyone know if it is possible to have a C++ class with overloaded operators such as +,-,* and declare it somehow (this is where the magic happens) to a QtScriptEngine such that js-expressions lik

Can someone point towards (or show) some good general floating point comparison functions in C# for comparing floating point values? I want to implement functions for IsEqual, IsGreater an IsLess. I a

I am trying to understand floating point inaccuracies and how to handle them in c#. I have looked at Floating point inaccuracy examples which gives some good answers, but I want to understand it speci

In C++, what is the keyword used to refer to a 32-bit floating point value?:

I know that I can not compare two floating point or double numbers for absolute equality on C++/C. If for some reason, I write a if condition which uses the absolute equality, is it guaranteed that th

I'm using C (not C++). I need to convert a float number into an int. I do not want to round to the the nearest number, I simply want to eliminate what is after the integer part. Something like 4.9 -&g

Could someone here please help me understand how to determine when floating point limitations will cause errors in your calculations. For example the following code. CalculateTotalTax = function (TaxR

I understand the complexities when using binary (or binaryoid) floating point and representing the result in decimal: 1 (do ((numerator 1 (* 10 numerator))) 2 ((>= numerator 1000000000000)) 3 (let

I'm searching with brute force for a floating point number with certain properties (small roundoff error of sin(a)^2+cos(a)^2-1). I therefore want to loop over the neighborhood of a given floating poi

What is the relevance of StackOverflow question/answer Why does changing 0.1f to 0 slow down performance by 10x? for Objective-C? If there is any relevance, how should this change my coding habi

Quoted from Effective Java - Second Edition by Joshua Bloch For floating-point fields, use Double.compare or Float.compare in place of the relational operators, which do not obey the general contract

http://www.learncpp.com/cpp-tutorial/25-floating-point-numbers/ I have been about this lately to review C++. In general computing class professors tend not to cover these small things, although we kne

I have an image processing program which uses floating point calculations. However, I need to port it to a processor which does not have floating point support in it. So, I have to change the program

Possible Duplicate: Trouble with floats in Objective-C I have broken this problem down to about as simple as i can get it. Feel free to try the same thing and tell me if you get the same error and w

I am not sure how to deal with floating point exceptions in either C or C++. From wiki, there are following types of floating point exceptions: IEEE 754 specifies five arithmetic errors that are to b

Is it possible to convert floating point exceptions (signals) into C++ exceptions on x86 Linux? This is for debugging purposes, so nonportability and imperfection is okay (e.g., if it isn't 100% guara

I have a python program that reads floating point values using the following regular expression (-?\d+\.\d+) once I extract the value using float(match.group(1)), I get the actual floating point num

I am looking for suggestions on how to find the sizes (in bits) and range of floating point numbers in an architecture independent manner. The code could be built on various platforms (AIX, Linux, HPU

I'm having some trouble with a problem I've run into dealing with floating points. I'm having a hard time moving from floating point representation to decimal values and also from format A of the repr

In C++ is it possible to define conversion operators which are not class members? I know how to do that for regular operators (such as +), but not for conversion operators. Here is my use case: I work

I have some places in my code where I want to assure that a division of 2 arbitrary floating point numbers (32 bit single precision) won't overflow. The target/compiler does not guarantee (explicitly

I set tow functions, one to enable exception for floating point and one to disable exception. In the code bellow, I have enabled tow exception in one time (_EM_ZERODIVIDE and _EM_OVERFLOW), after I ne

This is part of a macro I am writing in the ROOT framework using C++ and some predefined classes. I get a floating point exception upon including the lines marked below (starting with minv = ...). Wha

I tried to use google test framework and can't see why the following code: TEST(MathTest, BelowZeroCandF) { EXPECT_DOUBLE_EQ(convertCtoF(-1), 30.2); } where double convertCtoF(double c) { return 32+1

How can I make the following differentiate between signed numbers and floating point numbers? template<class T, typename std::enable_if<std::is_signed<T>::value>::type* = nullptr > c

I'm using floating point values as dictionary keys. Occasionally, very occasionally (and perhaps never, but not certainly never), there will be collisions. I would like to resolve these by incrementin

Possible Duplicate: Why doesn't C have unsigned floats? The question is probably very basic and probably answered many time earlier, but I want to understand why C++ does not have unsigned floating