473,324 Members | 2,456 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,324 software developers and data experts.

surprising results with subtration with floats on VC

See the following code :

#include <iostream>

using namespace std;

float f1 = 1.0e+6;

// This function just returns f1.
float value1()
{
return f1;
}

void main()
{
float f3 = f1 * f1 - f1 * f1;
cout<<"f3 = "<<f3<<endl;
float f4 = (f1 * value1()) - (f1 * value1());
cout<<"f4 = "<<f4<<endl;
}

The result is :
f3 = 0
f4 = -4096
I expected that the second result should also be zero, as
both are same.
But I am getting -4096.
Can you tell me the reason for this behavior.

The above behavior is not shown by double and long double.
Thanks,
pavan.

Nov 17 '05 #1
2 1166
"pavan" <an*******@discussions.microsoft.com> wrote in message
news:01****************************@phx.gbl...
See the following code :

#include <iostream>

using namespace std;

float f1 = 1.0e+6;

// This function just returns f1.
float value1()
{
return f1;
}

void main()
{
float f3 = f1 * f1 - f1 * f1;
cout<<"f3 = "<<f3<<endl;
float f4 = (f1 * value1()) - (f1 * value1());
cout<<"f4 = "<<f4<<endl;
}

The result is :
f3 = 0
f4 = -4096
I expected that the second result should also be zero, as
both are same.
But I am getting -4096.
Can you tell me the reason for this behavior.

The above behavior is not shown by double and long double.


The basic problem is that 1.0e12 cannot be represented
exactly in a float -- it doesn't have enough bits in the
mantissa. Your first calculation is carried out directly
in the floating-point registers, which have sufficient
bits in the mantissa to represent the intermediate results
in the calculation, so you get an exact answer. In the
second calculation, what happens is that the program
computes the results of "f1 * value1()" and then has to
save that value in a temporary before calling value1() again
to compute the other operand of "-". The temporary is a
float, which doesn't have enough bits to represent the value
exactly, so the intermediate result is rounded. The rounded
result is 4096 less than the exact value.

You can see that this is exactly what is happening by adding
the following to your code:

float f7 = f1 * f1;
float f8 = f7 - f1 * f1;
cout <<"f8 = "<<f8<<endl;

The printed result is "-4096", exactly as in your second
expression.

If you compile with "-Og" (which turns on global analysis
and common subexpression elimination), the function will only
be called once, so there's no need to store a temporary; the
entire calculation will be carried out in the floating point
registers and the result of both of your calculations will be
"0".

Welcome to the fun world of floating point rounding errors! :-)

-- William M. Miller
Nov 17 '05 #2
Thanks a lot for a very informational reply.

pavan.
Nov 17 '05 #3

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

Similar topics

2
by: Michael Cornelius | last post by:
As an old C programmer, I'm surprised by some results I'm getting with integer division. For example: >>> -1/1000 -1 >>> -9/2 -5 I expect the results of these expressions to be 0 and -4,...
8
by: Madhusudan Singh | last post by:
Is it possible to convert a very long list of strings to a list of floats in a single statement ? I have tried float(x) and float(x) but neither work. I guess I would have to write a loop if...
12
by: Jack | last post by:
Imagine if someone asked which of the follwing two methods of encoding an integer into a byte array was quicker. The purpose is in preparation for sending across a socket as part of a 'header'....
22
by: silversurfer2025 | last post by:
Hello everybdy, I am a little confused for the following reason: In my code I used a simple for-loop in order to initialize a 2D-array of floats to zero. Because of efficiency reasons, I changed...
2
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...
45
by: charles.lobo | last post by:
Hi, I have recently begun using templates in C++ and have found it to be quite useful. However, hearing stories of code bloat and assorted problems I decided to write a couple of small programs...
17
by: Dudely | last post by:
My web page displays just fine under IE7, but under IE6 about 90% of it is just plain missing. I get the top of the page, and the bottom of the page... but not the middle. I have not tested with...
16
by: luca bertini | last post by:
Hi, i have strings which look like money values (ie 34.45) is there a way to convert them into float variables? everytime i try I get this error: "numb = float(my_line) ValueError: empty string...
1
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 =...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

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.