473,794 Members | 3,056 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Float equality testing, Whidbey suggestion (Not A Bug)

A feature we'd like to see in VS 2004 is a compiler warning for equality
comparisons on floating values. Why? Because the behaviour allowed under the
ECMA spec is somewhat suprising. (Well it suprised us).

If you run the program below in debug mode (F5), it prints True. If you run
it in non-debug mode (Ctrl-F5), you get False.

We had a look at the ECMA spec (CLI - 12.1.3 line 35) and this behaviour
seems perfectly acceptable.

"Storage locations for floating point numbers (statics, array elements, and
fields of classes) are of fixed size. The supported storage sizes
are float32 and float64. Everywhere else (on the evaluation stack, as
arguments, as return types, and as local variables) floating point numbers
are represented using an internal floating-point type. In each such
instance, the nominal type of the variable or expression is either R4 or
R8, but its value may be represented internally with additional range
and/or precision. The size of the internal floating-point representation
is implementation-dependent, may vary, and shall have precision at least as
great as that of the variable or expression being represented."

A compiler warning for our admitted error would probably be a useful thing.
using System;

namespace FloatWeirdness
{

class Floaty
{
public Floaty( float a, float b )
{
_a = a;
_b = b;
}

public float Total
{
get
{
return _a + _b;
}
}
float _a, _b;
}

class Class1
{
static float storedValue;

[STAThread]
static void Main(string[] args)
{
Floaty floaty = new Floaty( 145.347519f, 6.878819f );
storedValue = floaty.Total;
Console.WriteLi ne( floaty.Total == storedValue );
Console.Read();
}
}
}

(NB According to 12.1.3 line 8 even storing the value in the static isn't
guaranteed to change the representation, but on our X86 VS.NET 2003, the
demo shows the problem).
Any thoughts?

Stu & Lee

Nov 15 '05 #1
2 4287
Forgot to add an even better tip...

NEVER EVER COMPARE FLOATING-POINT VALUES FOR EQUALITY!!!!

(Sorry for shouting but this is really important... and practically
everyone who is new to FP processing does it wrong.)

You must always compare FP values using some minimum threshold below
which they should be considered equal, and this threshold must be
greater than the smallest representable value for the least precise
variable or constant you're using, and also greater than whatever
error you anticipate your FP algorithm to introduce.

In your example, change this line:
Console.WriteLi ne( floaty.Total == storedValue );
to that line: Console.WriteLi ne(Math.Abs(flo aty.Total - storedValue) < 1e-5f);


and even better, use a symbolic constant for 1e-5. Now your program
should work correctly in both release & debug mode (it does for me).
Reducing this constant *just* to 1e-6 makes the program fail in
release mode, by the way -- that's how fiddly FP rounding is!

Obligatory links:
http://www.lahey.com/float.htm
http://docs.sun.com/source/806-3568/ncg_goldberg.html

This is all completely language-independent and also independent of
..NET, by the way. If you need decimal values without such problems
use the System.Decimal (C# decimal) data type... but it's slow and
doesn't have the range of values that float/double have.
--
http://www.kynosarges.de
Nov 15 '05 #2
On Thu, 7 Aug 2003 21:54:12 +0100, "Lee Alexander"
<leea@fuk_spam_ pobox.com> wrote:
Well in that case I would prefer a warning, and that's what Stu is getting
at. Time would have been saved if a warning came up whilst the code was
being written. It's an easy mistake to make and as such the compiler could
help to flag this type of mistake.


Okay, a warning about equality comparisons of FP values might be
useful but I don't know of any other compiler that produces such a
warning (though lint programs do). What I'm saying is, this is not a
C# or .NET issue -- you're simply expected to know such things when
you use floating-point algorithms.
--
http://www.kynosarges.de
Nov 15 '05 #3

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

Similar topics

6
2091
by: Bengt Richter | last post by:
Peculiar boundary cases: >>> 2.0**31-1.0 2147483647.0 >>> int(2147483647.0) 2147483647L >>> int(2147483647L ) 2147483647 >>> >>> -2.0**31
10
10296
by: Jesper Rønn-Jensen | last post by:
Hope you can help me out on this one. I have a a box that is floated right. Below (in the normal float) I have a wide table. <body> <div style="float:right; width:200px">...</div> <p>This paragraph is showed correctly</p> <table style="width:300px"> <tr><td>This table is not moved downwards in Firefox. </td></tr> <tr><td>IE gets it right.</td></tr>
2
1883
by: Michael Klatt | last post by:
I've been looking through the FAQ and Googling previous threads on c.l.c++ but I haven't seen this exact situation addressed. I initialize variables of type float to a known invalid value (of type const float), and at a later time I want to see if these variables are still undefined: #include <iostream> int main() { const float undefined(-999); // valid only as an initial value
26
3184
by: Alexander Block | last post by:
Hello newsgroup, let's say I have a function like template<class Type> inline bool areEqual(const Type &a, const Type &b) { return ( a == b ); }
5
3471
by: Jukka Lehtonen | last post by:
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
12
12457
by: shaanxxx | last post by:
I wanted to write hash function float or double. Any suggestion would be appreciated.
26
7143
by: neha_chhatre | last post by:
can anybody tell me how to compare two float values say for example t and check are two variables declared float how to compare t and check please help me as soon as possible
13
2455
by: helen.m.flynn | last post by:
Hi I'm very much a beginner with Python. I want to write a function to convert celcius to fahrenheit like this one: def celciusToFahrenheit(tc): tf = (9/5)*tc+32 return tf I want the answer correct to one decimal place, so celciusToFahrenheit(12) would return 53.6.
17
6812
by: D'Arcy J.M. Cain | last post by:
I'm not sure I follow this logic. Can someone explain why float and integer can be compared with each other and decimal can be compared to integer but decimal can't be compared to float? True True False This seems to break the rule that if A is equal to B and B is equal to C then A is equal to C.
0
10435
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10213
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
10163
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
10000
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
9037
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
6779
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5436
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
3721
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2920
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.