473,738 Members | 4,774 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Problems with multiplications of doubles and/or floats

Hi there,

I am trying to multiply doubles with floats (actually I tried every
possible combination by now) and it never works (well, it does something
but it is always wrong). I have no idea what it is and where to look for
help, maybe some of you know?

double=float*do uble; (or every possible combination of it). An example:

0.3 * 0.7 would result in 1.7 (with lots more digits). Anyone any idea?
If I change the types of the variables I think the result stays the same
(but I am not 100% sure)...

Jens

Jul 22 '05
43 2207

"J.K. Becker" <jk******@becke r.de> wrote in message
news:c5******** **@news1.zdv.un i-mainz.de...
I can't take the program apart, that would be more work than
reprograming the part that is not working. There is a reason for me not
to post the progam here, you know, believe me, if I could I would. I can
post the function here, but that is not going to help.
If you insist I will.


I'm not insisting on anything, just explaining how this group works. The
regulars here contribute a lot of their time for no recompense. I don't
think any have the time to take on the sort of in depth study that it sounds
like your problem needs.

You might have got lucky with you post and someone have recognised the
problem but you didn't so I guess there is no alternative but some hard work
on your part.

Post the function if you like, you never know it might help. One of the
things I've learned from this group is that posters are often convinced that
a problem is in some piece of code which they post (even though they don't
know what the problem is) but when after much resistence that are persuaded
to post more code, the problem turns out to have been in some part of the
code they were holding back.

John

BTW top posting is frowned on in this group.
Jul 22 '05 #11
J.K. Becker wrote:
[...]

J.K. Becker wrote:
[...]
double=float*do uble; (or every possible combination of it). An example:

0.3 * 0.7 would result in 1.7 (with lots more digits). Anyone any
idea? If I change the types of the variables I think the result stays
the same (but I am not 100% sure)...

Jens


If I'm understanding the problem correctly, this isn't a C++ problem, but an
implementation artifact.

Let's say that in your implementation, float has 6 digits of precision & double
has 12, so 0.3 is 0.300000, and 0.7 is 0.700000000000. These aren't integers
though, they are finite precision representations of real numbers, so 0.3 is
actually any number between 0.299999500000 and 0.300000499999. When the
generated code, or, more likely, the computer's Floating Point Hardware (FPU),
converts the 0.3 from float to double, it is perfectly entitled to convert it to
anything within its valid range.

Most people thing in base ten, so we intuitively expect that the 0.300000 will
be seamlessly converted into 0.300000000000. The FPU is probably constructed as
a binary device, and so it will still zero fill, but in binary. When converted
back to decimal, this gives some value that is close to, but not, exactly
0.300000000000. The value it gives is still correct though.

You can see how your compiler / FPU handle these conversions by single stepping
through this fragment.

float x = 0.3;

int main( int, char ** )
{
some_external_f n( &x ); // stop the optimizer making assumptions about x
double y = x;
std::cout << y << std::eol;
return 0;
}

Regards

Bruce

Jul 22 '05 #12
John Harrison wrote:
"J.K. Becker" <jk******@becke r.de> wrote in message
news:c5******** **@news1.zdv.un i-mainz.de...
I can't take the program apart, that would be more work than
reprogramin g the part that is not working. There is a reason for me not
to post the progam here, you know, believe me, if I could I would. I can
post the function here, but that is not going to help.
If you insist I will.

I'm not insisting on anything, just explaining how this group works. The
regulars here contribute a lot of their time for no recompense. I don't
think any have the time to take on the sort of in depth study that it sounds
like your problem needs.

You might have got lucky with you post and someone have recognised the
problem but you didn't so I guess there is no alternative but some hard work
on your part.

Post the function if you like, you never know it might help. One of the
things I've learned from this group is that posters are often convinced that
a problem is in some piece of code which they post (even though they don't
know what the problem is) but when after much resistence that are persuaded
to post more code, the problem turns out to have been in some part of the
code they were holding back.

John

BTW top posting is frowned on in this group.


I know that it is not a simple error (well, it might be but I have no
idea where). The program consits of, I don't know, 10000 lines or more,
something like 100 and more seperate files. And to make it more fun, it
has grown over the years so some files are c++ (OO), some are c++ (not
OO), some c and some fortran. And it has been written by people in the
US, Australia, UK, Germany (that's me) and France. So no way to strip
that down to something everybody can understand quickly.
But since we all are running out of ideas on what and where to look, I
thought I'd try here.

Jens

Jul 22 '05 #13
This is the function where the error occurs. As you can see there are a
lot of calculations in it, they all work fine except the one mentioned
(which seems to be the easiest one).

Fx = un.x * dEdp;
Fy = un.y * dEdp;

This always gives the wrong results... Everything before it works and
everything after it works too (except that everything is calculated with
the wrong values for Fx and Fy).
But I guess it is too complex for a quick fix...
Thanks anyway

Jens
int GBE_MoveNode( int index, Coords * movedir )
{
int i, l, k, moveflag = 0;
double E1, E2, E3, E4, vangle[3],lenL[3] , lenK[3];
double truetimestep = 3.1536e10;
float Fx,Fy;
double lenP, lenV, lenF, mobility1, mobility2, mobility3 , switchd;
Coords p1, p2, gvector, un, sigma1, sigma2, sigma3, L[3], F;
Coords newxy, xynb, xy, prev, V;
float dEdp;
int nb[3];
char cc[255];

mobility1 = 1e-12;
mobility2 = 1e-12;
mobility3 = 1e-12;

switchd = ElleSwitchdista nce() / 10;
//Get position of first node
ElleNodePositio n( index, & p1 );
ElleNodePrevPos ition( index, & prev );

//this is the first energy we need: E((x+dx),y)
p2.x = p1.x + switchd;
p2.y = p1.y;
ElleSetPosition ( index, & p2 );
GetNodeEnergy( index, & p2, & E1 );

//this is the second energy we need:E((x-dx),y)
p2.x = p1.x - switchd;
p2.y = p1.y;
ElleSetPosition ( index, & p2 );
GetNodeEnergy( index, & p2, & E2 );

//this is the third energy we need: E(x,(y+dy))
p2.x = p1.x;
p2.y = p1.y + switchd;
ElleSetPosition ( index, & p2 );
GetNodeEnergy( index, & p2, & E3 );

//this is the fourth energy we need: E(x,(y-dy))
p2.x = p1.x;
p2.y = p1.y - switchd;
ElleSetPosition ( index, & p2 );
GetNodeEnergy( index, & p2, & E4 );

//Reset node position to starting values
ElleSetPosition ( index, & p1 );
ElleSetPrevPosi tion( index, & prev );

//So now we can calculate the gradient vector (P)
gvector.x = ( E1 - E2 ) / ( 2 * switchd );
gvector.y = ( E3 - E4 ) / ( 2 * switchd );
if ( gvector.x == 0.0 && gvector.y == 0.0 )
{
movedir->x = 0.0;
movedir->y = 0.0;
return ( 0 );
}
else
{
//reverse gradient
gvector.x *= -1;
gvector.y *= -1;
//length of gradient
lenP = sqrt( ( gvector.x * gvector.x ) + ( gvector.y * gvector.y ) );
//unit vector
un.x = gvector.x / lenP;
un.y = gvector.y / lenP;
dEdp = ( ( gvector.x / gvector.y ) + ( gvector.y / gvector.x ) ) /
lenP;

////////
//////// wrong results in this calculation
////////
Fx = un.x * dEdp;
Fy = un.y * dEdp;
////////
////////
////////

lenF = sqrt( ( Fx * Fx ) + ( Fy * Fy ) );
ElleNeighbourNo des( index, nb );
for ( i = 0, k = 0; i < 3; i++ )
{
if ( nb[i] != NO_NB && ElleNodeIsActiv e( index ) )
{
ElleNodePositio n( nb[i], & xynb );
L[k].x = p1.x - xynb.x;
L[k].y = p1.y - xynb.y;
lenL[k] = sqrt( ( L[k].x * L[k].x ) + ( L[k].y * L[k].y ) );
vangle[k] = fabs(90- ( acos( ( Fx * L[k].x + Fy * L[k].y ) / (
lenL[k] * lenF ) ) ));
lenK[k] = lenL[k] * fabs( sin( vangle[k] * ( 180 / 3.1415926535
) ) );
k++;
}
}
sigma1.x = Fx / ( lenK[0] + ( mobility1 / mobility2 ) * lenK[1] );
sigma1.y = Fy / ( lenK[0] + ( mobility1 / mobility2 ) * lenK[1] );
V.x = sigma1.x * (mobility1/switchd/switchd);
V.y = sigma1.y * (mobility1/switchd/switchd);
lenV = sqrt( ( V.x * V.x ) + ( V.y * V.y ) );
movedir->x = p1.x - V.x;
movedir->y = p1.y - V.y;
moveflag = 1;
return ( moveflag );
}
}

Jul 22 '05 #14
Bruce Clement wrote:
If I'm understanding the problem correctly, this isn't a C++ problem,
but an implementation artifact.

Let's say that in your implementation, float has 6 digits of precision &
double has 12, so 0.3 is 0.300000, and 0.7 is 0.700000000000. These
aren't integers though, they are finite precision representations of
real numbers, so 0.3 is actually any number between 0.299999500000 and
0.300000499999. When the generated code, or, more likely, the computer's
Floating Point Hardware (FPU), converts the 0.3 from float to double, it
is perfectly entitled to convert it to anything within its valid range.

Most people thing in base ten, so we intuitively expect that the
0.300000 will be seamlessly converted into 0.300000000000. The FPU is
probably constructed as a binary device, and so it will still zero fill,
but in binary. When converted back to decimal, this gives some value
that is close to, but not, exactly 0.300000000000. The value it gives is
still correct though.

You can see how your compiler / FPU handle these conversions by single
stepping through this fragment.

float x = 0.3;

int main( int, char ** )
{
some_external_f n( &x ); // stop the optimizer making assumptions
about x
double y = x;
std::cout << y << std::eol;
return 0;
}

Regards

Bruce


I thought about that too, but the error is to big to be a rounding
problem (well I think). 0.3 *0.7 can give something 0.2100012383897 41291
(just an example) which would be fine with me, but not 1.72094230948.
The error is just too big. It is interesting to note though that it
always calculates the same so it does not multiply arbitrary numbers
that it gets from memory somewhere, but always the same numbers....

Jens

Jul 22 '05 #15
Is there the slightest chance that the debugger shows wrong values but
the calculation acutally uses the right ones? (gdb/ddd)

See how desperate I am?!

Jens

Jul 22 '05 #16
J.K. Becker wrote:

[...]

I thought about that too, but the error is to big to be a rounding
problem (well I think). 0.3 *0.7 can give something 0.2100012383897 41291
(just an example) which would be fine with me, but not 1.72094230948.
The error is just too big. It is interesting to note though that it
always calculates the same so it does not multiply arbitrary numbers
that it gets from memory somewhere, but always the same numbers....


OK,

Jens, please don't take what follows as dismissive or demeaning. I've been
making my living from developing code for over 25 years, and when I don't
understand the problem I find it makes sense to go back to basics & attempt to
double check that I've eliminated all the obvious problems.

So let's look at it in context.

////////
//////// wrong results in this calculation
////////
Fx = un.x * dEdp;
Fy = un.y * dEdp;
////////
////////
////////

Presumably this means that when un.x = 0.3 and dEdp = 0.7 that Fx becomes
1.7209423...

If that's the case, there's only a very few possibilities:
1. The prerequisites are not met (either un.x != 0.3 or dEdp != 0.7)
2. The result isn't what you think it is (Fx does = 0.21) and something else is
wrong
3. The debugger is confused (I've seen this happen with optimised code)
4. The compiler is generating bad code
5. You've uncovered a hardware bug in the FPU.
...

1 & 2 can be eliminated by breaking the program at this step & examining
variables before & after the assignments

If 3 is a possibility, try switching into machine code & tracing the statement
through at the instruction level. You may find that the variables being loadedd
/ stored aren't what you expected.

4 & 5 Are very unlikely, but can be eliminated as possibilities by debugging at
machine instruction level as per 3.
Good Luck

Bruce

Jul 22 '05 #17
J.K. Becker wrote:
Is there the slightest chance that the debugger shows wrong values but
the calculation acutally uses the right ones? (gdb/ddd)

See how desperate I am?!

Jens

Yes,

I've seen this in debuggers especially when dealing with optimised code. The
windows VC6 compiler was especially bad (thought 'this' was in a different
register to the one it was actually in).

You need to make sure you've compiled up for debugging.

I've also seen it in GDB when the compile failed (I'd missed that it had a
compile error :( )

B.

Jul 22 '05 #18
Bruce Clement wrote:

[snip]

Presumably this means that when un.x = 0.3 and dEdp = 0.7 that Fx
becomes 1.7209423...

If that's the case, there's only a very few possibilities:
1. The prerequisites are not met (either un.x != 0.3 or dEdp != 0.7)
2. The result isn't what you think it is (Fx does = 0.21) and
something else is wrong
3. The debugger is confused (I've seen this happen with optimised code)
4. The compiler is generating bad code
5. You've uncovered a hardware bug in the FPU.
...

1 & 2 can be eliminated by breaking the program at this step & examining
variables before & after the assignments

If 3 is a possibility, try switching into machine code & tracing the
statement through at the instruction level. You may find that the
variables being loadedd / stored aren't what you expected.

4 & 5 Are very unlikely, but can be eliminated as possibilities by
debugging at machine instruction level as per 3.
Good Luck

Bruce

Ah, don't worry, these are the kind of tips I was looking for! I had a
look with a debugger and I am using makeg, so I guess #1 is unlikely. I
agree that I have not found a hardware error (oh how I wish that would
be the case: "See, it is not my fault, there is nothing I can do, it is
IBM and AMD's fault...." :-) ).
I will try to debug the whole thing with machine code, although I really
have no idea yet if that is going to help me (my assembler-skills are,
well, rudimentary would be a compliment). But I think that is the best
way to go for now

If you can think of anything else....

Thanks

Jens

Jul 22 '05 #19

"J.K. Becker" <jk******@becke r.de> wrote in message
news:c5******** **@news1.zdv.un i-mainz.de...
Is there the slightest chance that the debugger shows wrong values but
the calculation acutally uses the right ones? (gdb/ddd)


That's entirely possible. Have you tried dumping the values out to a file?

john
Jul 22 '05 #20

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

Similar topics

9
2572
by: Yaroslav Bulatov | last post by:
I made an array of 10 million floats timed how long it takes to sum the elements, here's what I got (millis): gcc -O2: 21 Python with numarray: 104 Python with Numeric: 302 java: 325 gcc: 348 Python with Psyco: 1317 Pure Python using sum: 2312
3
1446
by: dave | last post by:
I'm trying to learn this. My problem, I have 2 strings that represent floats. I want to add them together. Should I look at using Cint to convert each character in the string and add individually? or would grouping the "digits" in the string by say 10 or 20 and working the smaller parts? Would i loose something by grouping in that way? Or is there a faster/better way? I have been thinking about this for a while and I don't want to start...
6
2546
by: Amit Bhatia | last post by:
Hello everyone. Sorry to be cross posting this on comp.lang.c++ (moderated) This is a simple question that is causing some problem in one of the classes that I have designed. I have two doubles: double a=2.4; double b=0.15; const double VERYTINY = 1.e-30; \\I define how small is small here;
14
1681
by: my.correo.basura | last post by:
Yesterday I found in a piece of code a float being incremented with ++. For some reason (wrong, I guess...) I thought that only integer types could be incremented that way, and I had never seen floats or doubles incremented that way before. Just to be sure I did a toy program and compiled with gcc -ansi -pedantic -Wall and it worked without any error or warning, showing the correct result. Is it correct to increment floats or doubles with...
6
8720
by: Mike P | last post by:
Why does this cause the error 'cannot implicitly convert type 'double' to 'float'? Can you not multiply doubles by floats without converting them all to the same datatype? fltPCRateStd = fltPCRateStd * 1.175; Regards, Mike
10
2429
by: abdul_n_khan | last post by:
I have a basic question related to datatype conversion. I am multiplying currency to float datatype. fltInterestRate=1.23333; curAmount = 91000000; curInterestAmount = curAmount * fltInterestRate curInterestAmount should have 112233030
7
3888
by: SpreadTooThin | last post by:
I have some code... import array a = array.array('d') f = open('file.raw') a.fromfile(f, 10) now I need to convert them into floats (32 bit...) what do i do?
6
2911
by: Pavel | last post by:
Hello, Does anyone know a (preferably open-source) multi-platform C or C++ library that would be able to write and read C/C++ doubles and floats to/from streambuf, char array or similar device in IEEE 754 with reasonably optimal precision and performance? The purpose is to exchange serialized doubles and floats between C/C++ and Java programs where Java serialization rules are used.
3
1931
by: jerry.teshirogi | last post by:
I have the following class and main: ////////////////////////////////////////////////////////// #include <iostream.h> class myVector { public: double x, y, z:
0
8969
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
8788
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,...
1
9263
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
8210
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...
1
6751
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6053
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
4825
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3279
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
2745
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.