View previous topic :: View next topic |
Author |
Message |
JackK
Joined: 16 Oct 2020 Posts: 5
|
Multiplying large single precision numbers |
Posted: Fri Jan 08, 2021 3:10 pm |
|
|
Hi
I'm not a programmer and know just enough to get me in trouble. I have been tasked to see if I could resolve a problem with a product of ours. The issue is, we are multiplying 2 single precision numbers. The result can be very large so I test.
We are using a pic18F67K90. This is the Test program I used:
Code: | float num1;
float num2;
float ans;
num1=100000;
num2=100000;
ans=num1*num2;
fprintf(AUX_UART,"\r\nTestTotal=%f",ans); |
This is the answer:
TestTotal=-7273838.52
Why is this like this and can anyone tell me what I'm doing wrong.
Thanks
Jackk |
|
|
temtronic
Joined: 01 Jul 2010 Posts: 9221 Location: Greensville,Ontario
|
|
Posted: Fri Jan 08, 2021 3:29 pm |
|
|
quick comment...
My 'gut' feeling it's actually a printing error or limit not a 'math' problem. Others will know for sure. Perhaps format the print for 'exponential' display ?
Maybe try smaller numbers, test, try a bigger number, test, see where it fails...? |
|
|
newguy
Joined: 24 Jun 2004 Posts: 1907
|
|
Posted: Fri Jan 08, 2021 3:34 pm |
|
|
What compiler version? I don't know about recent compilers, but I do know that in the past, there were versions that had trouble with printf and fprintf properly formatting floats.
To check, print out the float as bytes, in hex. You can then check the result using an online tool or the compiler's base converter utility.
For example, 10,000,000,000 in Microchip float 32 format is 0xF9 02 15 A0. See if the individual bytes that compose the float are correct - if they are, what you're seeing is a printf/fprintf bug. |
|
|
Ttelmah
Joined: 11 Mar 2010 Posts: 19499
|
|
Posted: Sat Jan 09, 2021 8:53 am |
|
|
Critical question. What compiler version?.
I remember there was an issue a while ago, with %f. It would work fine
if you gave it a 'size', but not if you used it without a size. So
try something like %7.1f, instead of just %f.
I think this is what Newguy is also remembering.
Yes, can confirm. Anything larger than about 20000000, won't be handled
by the %F output. You have to switch the %E and use exponential notation
beyond this.
It will work a bit further if you specify a size, but even this fails before the
11 digits needed here. |
|
|
JackK
Joined: 16 Oct 2020 Posts: 5
|
Multiplying large single precision numbers |
Posted: Tue Jan 12, 2021 9:26 am |
|
|
You all are correct in the print function. had to change it to %e and everything works fine. Thanks for all your help. |
|
|
|