473,804 Members | 3,697 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

operator== (float, float)

Hi all,

I was watching g++ to spurt out warnings during compilation,
and if you enable most warning flags as I have occasionally
done that means a lot of text, most of it from library code.
Nothing special, but then I started thinking about the
occasional 'comparing floats for equality' lines.

I admit that those warnings are an indicator of my own
lazyness. The technical reasons for a call

float A = ...; float B = ...; if ( A == B ) ...

to be suspicious are a FAQ, as is the solution

if ( fabs( A - B ) < epsilon ) ...

The question that formed in my mind was:

Why do I have to do that?

What is the purpose of operator== (float, float)
within the standard if it does not perform the action
that my intuition expects? Granted, the epsilon would have
to be specified somewhere.

JVL
--
Be reading you.

mailto:Ju****** ******@abo.fi
Jul 22 '05 #1
5 3472

"Jukka Lehtonen" <Ju************ @abo.fi> wrote in message
news:t0******** *****@olvi.abo. fi...
Hi all,

I was watching g++ to spurt out warnings during compilation,
and if you enable most warning flags as I have occasionally
done that means a lot of text, most of it from library code.
Nothing special, but then I started thinking about the
occasional 'comparing floats for equality' lines.

I admit that those warnings are an indicator of my own
lazyness. The technical reasons for a call

float A = ...; float B = ...; if ( A == B ) ...

to be suspicious are a FAQ, as is the solution

if ( fabs( A - B ) < epsilon ) ...

The question that formed in my mind was:

Why do I have to do that?

What is the purpose of operator== (float, float)
within the standard if it does not perform the action
that my intuition expects? Granted, the epsilon would have
to be specified somewhere.


Well I'm not sure what you expect but operator== (float, float) does exactly
what I would expect, it compares two floats for equality. The problem is
that floating point arithmetic is often inexact, not that equality between
floating point numbers is ill defined.

There are occasions when exact floating point equality is useful. For
instance the following tests if a double has an integral value

double x = func();
if (x == floor(x))
cout << "is integral\n";
else
cout << "is not integral\n";

If operator== was redefined in the way you suggest code like that would no
longer work.

john
Jul 22 '05 #2
Jukka Lehtonen wrote in news:t0******** *****@olvi.abo. fi in comp.lang.c++:
Hi all,

I was watching g++ to spurt out warnings during compilation,
and if you enable most warning flags as I have occasionally
done that means a lot of text, most of it from library code.
Nothing special, but then I started thinking about the
occasional 'comparing floats for equality' lines.

I admit that those warnings are an indicator of my own
lazyness. The technical reasons for a call

float A = ...; float B = ...; if ( A == B ) ...

to be suspicious are a FAQ, as is the solution

if ( fabs( A - B ) < epsilon ) ...

The question that formed in my mind was:

Why do I have to do that?

What is the purpose of operator== (float, float)
within the standard if it does not perform the action
that my intuition expects? Granted, the epsilon would have
to be specified somewhere.


Alas there is no "One True Way" when it comes to doing any kind
of floating-point.

if ( fabs( A - B ) < epsilon ) ...

Also has a problem, say epsilon is 1.0, but A and B > 1E20 (*). The
only way the epsilon-equality form can be true is if the exact-equality
form is true.

So your left with exact equality being the only meaningfull, consistant
and general purpose meaning you can give to operator ==.

*) 1e20, I'm assuming float has a max precision of 19 decimals here.

Rob.
--
http://www.victim-prime.dsl.pipex.com/
Jul 22 '05 #3
Jukka Lehtonen wrote:

Hi all,

I was watching g++ to spurt out warnings during compilation,
and if you enable most warning flags as I have occasionally
done that means a lot of text, most of it from library code.
Nothing special, but then I started thinking about the
occasional 'comparing floats for equality' lines.

I admit that those warnings are an indicator of my own
lazyness. The technical reasons for a call

float A = ...; float B = ...; if ( A == B ) ...

to be suspicious are a FAQ, as is the solution

if ( fabs( A - B ) < epsilon ) ...

The question that formed in my mind was:

Why do I have to do that?


You might want to read

http://www.petebecker.com/js200006.html
http://docs.sun.com/source/806-3568/ncg_goldberg.html

Oh, and by the way:
Don't use float until you know exactly what you do and have a very good
reason to do it and know how to fight that beast.
Use double instead. The problems are not gone away but are a little
bit smaller. Often small enough that for practical purposes it is
the difference between a tough fight and a smooth walk.

--
Karl Heinz Buchegger
kb******@gascad .at
Jul 22 '05 #4
Jukka Lehtonen wrote:

if ( fabs( A - B ) < epsilon ) ...

The question that formed in my mind was:

Why do I have to do that?

What is the purpose of operator== (float, float)
within the standard if it does not perform the action
that my intuition expects? Granted, the epsilon would have
to be specified somewhere.


The problem is, that epsilon varies..It depends on A and B *and* the
rounding error you are ready to expect at a certain state of
computation. Refer to numeric_limits< T>::epsilon(). This returns the
smallest number, such that 1.0 + epsilon == 1.0. But this also means
(usually...), that for any other number r, epsilon is r*epsilon!

Now consider something like x*x. if x has an epsilon eps(x), then x*x
has a maximal error of something like[1]:

error(x*x)=|(x+ eps(x))^2-x^2|=|2*x*eps(x )+eps(x)^2|

and for (x*x)/x it's |error(x^2)/(x+eps)-error(x^2)/x|

So therefore you need an idea for you epsilon or make a good guess.

Marco

[1] Disclaimer: These formulas a incorrect and irrelevant and are meant
to give nothing than a rough idea of the magnitude of expectable
trouble.

Jul 22 '05 #5
Thank you for the answers. I was aware of the rounding
as binary values can not represent all decimal values
exactly, but the relation of magnitude of values to the
errors induced by operations was new.

Back to the drawing board...

JVL
--
Be reading you.

mailto:Ju****** ******@abo.fi
Jul 22 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

21
2196
by: Makhno | last post by:
Hello, Why does my cast from Vector<class Float> to Vector<float> not work? It won't compile, template<class Float> class Vector { public: Vector(Float x1,Float y1,Float z1):x(x1),y(y1),z(z1){} inline Vector<float> operator() () const;
34
6473
by: Pmb | last post by:
I've been working on creating a Complex class for my own learning purpose (learn through doing etc.). I'm once again puzzled about something. I can't figure out how to overload the assignment operator. Here's what I'm trying to do. I've defined class Complex as class Complex { friend ostream &operator<<( ostream &, Complex & ); public: Complex( float = 0.0, float = 0.0 );
4
2231
by: Dan | last post by:
Hi, I would just like to know if the istream operator takes only one parammeter(object) at a time (like z) ? istream operator>>(istream& in, Shape &z) Cause I keep getting error concerning the amount my operator has for bother cin , cout operator<< and >> thanks Dan
11
1582
by: Michael | last post by:
Hi, As an exercise, I created a class C that duplicates a value x thus having x_val1 and x_val2 I also overrided the + operator so that if I have z = x + y (x,y and z belong class C) then + performs z_val1 = x_val1 + y_val1 z_val2 = x_val2 + y_val2 This works fine but it doesn't allow more than one addition per
9
2211
by: SpoonfulofTactic | last post by:
I am working on a new library for my own use that would allow me to use SI Units and to convert them back and forth with ease. However, While I have been working on operator overloading, I have come accross a problem: If I want to be able to simplify units through operators, I end up with inter-dependant classes.
6
2100
by: Arne Schmitz | last post by:
I guess this has been asked before, but I cannot find any answer to this problem. I have program like this: ---SNIP--- #include <cassert> #include <cstdlib> class C { public:
2
3045
by: Steffen | last post by:
Hi, is there a simple way to use operators overloaded in some class for objects of a derived class? In my example I have a class Matrix that represents 2x2 matrices, and I overloaded operator= and operator+ for this class. Then there is a derived class DiagonalMatrix which represents diagonal 2x2-matrices. Now I would like to use the operators = and + also for the diagonal matrices, but the naive way doesn't work:
5
2758
by: Fei Liu | last post by:
Hi, I have a interesting problem here, class absOP{ template<class T> T operator(T val) { return val < 0 ? -val : val; } }; Now the problem is I can't seem to use this overloaded operator, absOP op(..);
12
2211
by: cody | last post by:
Why can I overload operator== and operator!= separately having different implementations and additionally I can override equals() also having a different implementation. Why not forbid overloading of == and != but instead translate each call of objA==objB automatically in System.Object.Equals(objA, objB). This would remove inconsistencies like myString1==myString2
22
3631
by: clicwar | last post by:
A simple program with operator overloading and copy constructor: #include <iostream> #include <string> using namespace std; class Vector { private: float x,y; public: Vector(float u, float v);
0
9706
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9579
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10332
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10320
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10077
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9150
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5651
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3820
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2991
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.