473,769 Members | 2,116 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Unexpected results while working with floats

I ran the following simple code in C++ and got unexpected results:

float f = 139.4;
cout << f;

Output:
139.399994;

if( f == 139.4)
cout << "Expected result";
else
cout << "Unexpected result";

Output:
Unexpected reult
I ran the following equivalent code in VB but got the correct results.

Dim f As Single
f = 139.4

Print f
If f = 139.4 Then
Print "Expected result"
Else
Print "Unexpected result"
End If
Doesn't this look bad on C++'s resume?
Jun 27 '08
13 3619
On May 13, 2:04*am, Lionel B <m...@privacy.n etwrote:
On Tue, 13 May 2008 08:55:23 +0000, Lionel B wrote:
On Mon, 12 May 2008 16:02:54 -0700, Greg Herlihy wrote:
On May 12, 3:08*pm, Lionel B <m...@privacy.n etwrote:
>On my system (compiler GCC 4.1.2) with
>* float f = 139.4;
>and compiled with:
>* g++ -std=c++98 -pedantic -Wall -Wextra
>I get no warnings and the output is 'Expected result'. Should the
compiler warn if there's an implicit conversion? Or only if it results
in loss of precision?
The g++ compiler can issue a warning if you want one:
* *g++ -Wshorten-64-to-32
cc1plus: error: unrecognized command line option "-Wshorten-64-to-32"
GCC 4.3.0 on x86_64
Anyway, that doesn't sound like a floating-point warning...

This does it: -Wconversion. With

* float f = 139.4;

warning: conversion to ‘float’ alters ‘double’ constant value
On my machine, using gcc (version 4.2.1 (Apple Inc. build 5559)) -
Wconversion reports nothing.
Whereas -Wshorten-64-to-32 reports:

warning: implicit conversion shortens 64-bit value into a 32-bit
value

Greg
Jun 27 '08 #11
On Tue, 13 May 2008 02:50:53 -0700, Greg Herlihy wrote:
On May 13, 2:04Â*am, Lionel B <m...@privacy.n etwrote:
>On Tue, 13 May 2008 08:55:23 +0000, Lionel B wrote:
On Mon, 12 May 2008 16:02:54 -0700, Greg Herlihy wrote:
>On May 12, 3:08Â*pm, Lionel B <m...@privacy.n etwrote:
>>On my system (compiler GCC 4.1.2) with
>>Â* float f = 139.4;
>>and compiled with:
>>Â* g++ -std=c++98 -pedantic -Wall -Wextra
>>I get no warnings and the output is 'Expected result'. Should the
compiler warn if there's an implicit conversion? Or only if it
results in loss of precision?
>The g++ compiler can issue a warning if you want one:
>Â* Â*g++ -Wshorten-64-to-32
cc1plus: error: unrecognized command line option "-Wshorten-64-to-32"
GCC 4.3.0 on x86_64
Anyway, that doesn't sound like a floating-point warning...

This does it: -Wconversion. With

Â* float f = 139.4;

warning: conversion to ‘float’ alters ‘double’ constant value

On my machine, using gcc (version 4.2.1 (Apple Inc. build 5559)) -
Wconversion reports nothing.
Whereas -Wshorten-64-to-32 reports:

warning: implicit conversion shortens 64-bit value into a 32-bit
value
Sure, I see that -Wshorten-64-to-32 is a Mac thing - it's all going to be
highly machine-specific. I'm surprised -Wconversion doesn't report
anything, though.

--
Lionel B
Jun 27 '08 #12
bintom wrote:
float f = 139.4;
if( f == 139.4)
You are converting a 64-bit floating point number into a 32-bit one,
and then comparing the result to a 64-bit one. All bets are off.

The difference with some other languages is that C++ doesn't try to
second-guess what you are really trying to do, and it does what and only
what you asked it to do.

That the equality comparison is giving false is a result of the
underlying hardware and the floating point format used, not a flaw in
C++. The underlying hardware is dropping some bits from this value in
question when you are making the 64->32 bit conversion. When you try to
compare it to the original 64-bit value, the result will be different.
Jun 27 '08 #13
A big thanks to Erik and Juha for showing me where I was going wrong.
You saved my day.
Jun 27 '08 #14

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

Similar topics

3
7423
by: Eric Anderson Vianet SAO | last post by:
hello all When i tried ´pg_dump -v -f dump.dmp dtbtransporte´ I got the error: pg_dump: restoring data for table tbdmovimento pg_dump: dumping out the contents of table tbdmovimento pg_dump: ERROR: unexpected chunk number 8 (expected 0) for toast value 6935693
3
11075
by: user_5701 | last post by:
Hello, I'm getting an error with a Docmd.Transferspreadsheet line of code: DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel2000, "tblTest", pathAndFilename, True The above line works perfectly fine, but when I change the table name argument (tblTest) to the name of a query, it fails and gives the following error:
3
1445
by: rimmer | last post by:
I'm writing an extension module in C in which I'm passing an array of floats from C to python. The code below illustrates a simple C function designed to output an array of floats. --------- extTest.c --------- #include <stdio.h> double *testArray(int nsamp) {
2
5446
by: Martijn Mulder | last post by:
/* GraphicsPath.IsVisible() gives unexpected results. I fill a System.Drawing.Drawing2D.GraphicsPath-object with PointF-structures that define the unit-square (0,0), (1,0), (1,1) and (0,1). Then I test 3 different PointF-structures to see if they fall inside the unit- square and the results are clearly wrong: Point(-0.2, -0.2) falls inside the unit square... WRONG!!! Point(0.2, 0.2) falls inside the unit square... Point(0.7, 0.7) falls...
11
1628
by: hogtiedtoawaterbuffalo | last post by:
I have a template class that works fine when I implement it with <int>, but when I use <floator <doubleit doesn't work. The class has a dynamic array of type T that gets instantiated in my constructor. When type T is int, the array works like I expect. But when I use double or float, the array points to garbage and any updates to array elements make no difference. I'm using Visual Studio 2005 on an XP pro machine. The following is...
23
1702
by: gu | last post by:
hi to all! after two days debugging my code, i've come to the point that the problem was caused by an unexpected behaviour of python. or by lack of some information about the program, of course! i've stripped down the code to reproduce the problem: <code> a = {} for x in range(10):
1
2000
by: digidave | last post by:
I am keenly aware that my coding skills are extremely noob but please indulge me a second.. Take a look at these queries.. $sql = "SELECT DISTINCT year FROM _current_floats_config WHERE active = 'yes' ORDER BY year DESC LIMIT 2, 1"; $result = mysql_query($sql); while($fetched = mysql_fetch_array($result)) { $ceiling = $fetched; } $sql = "SELECT * FROM _current_floats WHERE active = 'yes' AND yearID <= $ceiling ORDER BY yearID...
2
1798
by: =?Utf-8?B?d2R1ZGVr?= | last post by:
I have a website using windows integrated security, with anonymous access turned off. The site is used to query orders from a database and when the search takes a long time, a windows login box appears. Regardless of what login the user enters into this, it does not accept it and the user is locked out of the system. Our network team and myself have been unable to find out why this is occurring, has anyone else had a similiar problem?...
0
9422
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
10208
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
10038
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
9987
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
9857
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
8867
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
6662
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();...
1
3952
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3558
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.