![]() |
|
|
|
|
|||||||
| Forums | Portal | Register | Forum Rules | FAQ | Contribute | Members List | Arcade | Search | Today's Posts | Mark Forums Read |
| High Level Programming Post questions about C, C++, Java, SQL, and other programming languages here. |
|
|
||||
| Thread | Thread Starter | Forum | Replies | Last Post |
| Rounding off the value of Floating point value | damansingh | Shell Programming and Scripting | 7 | 05-21-2008 06:46 AM |
| Floating point exception !!! | ssk01 | Linux | 2 | 05-14-2008 02:58 AM |
| floating point problem | vijlak | High Level Programming | 4 | 03-08-2007 01:18 AM |
| floating point addition | ravi raj kumar | Shell Programming and Scripting | 8 | 12-21-2006 11:47 PM |
| Floating Point Division | gsatch | Shell Programming and Scripting | 1 | 07-25-2002 01:03 PM |
|
|
Submit Tools | LinkBack | Thread Tools | Search this Thread | Display Modes |
|
#1
|
|||
|
|||
|
Floating point error in C
Hi,
see the simple code below double i; i=8080.9940; printf(" val :%.30f\n",i); output i m getting is val :8080.993999999999700000000000000 when i m expecting val :8080.9940 what happens?how can i avoid it? thanks... |
| Forum Sponsor | ||
|
|
|
#2
|
||||
|
||||
|
Floating point numbers have a complex representation using base 2 rather than base 10. Scientific notation is close enough to understand what is happening. With scientific notation, we want a number between 1 and 10 multiplied by a power of 10: 8080.9940 = 8.0809940 * 10^3 and we can check that out with bc:
Code:
$ bc bc 1.03 (Nov 2, 1994) Copyright (C) 1991, 1992, 1993, 1994 Free Software Foundation, Inc. This is free software with ABSOLUTELY NO WARRANTY. For details type `warranty'. 8.0809940 * 10^3 8080.9940000 ^D$ Code:
$ bc -l bc 1.03 (Nov 2, 1994) Copyright (C) 1991, 1992, 1993, 1994 Free Software Foundation, Inc. This is free software with ABSOLUTELY NO WARRANTY. For details type `warranty'. obase=2 scale=40 8080.9940/4096 1.111110010000111111100111011011001000101101000011100101011000000100\ 0001100010010011011101001011110001101010011111101111100111011011001 l(4096)/l(2) 1100.000000000000000000000000000000000000000000000000000000000000000\ 00000000000000000000000000000000000000000000000000000000000000000000\ 00 obase=10 ibase=2 1.1111100100001111111001110110110010001011010000 * 10^1100 8080.9939999999478459358215332031250000000000000000 1.11111001000011111110011101101100100 * 10^1100 8080.99399995803833007812500000000000000 |
|
#3
|
||||
|
||||
|
Hi,
You can try this code and will give the exact output which you are expecting double i; i=8080.9940; printf(" val :%.4f\n",i); Why because if you given %.30f it will consider 30 digit for fraction value so instead of %.30f we can use %.4f. Let me know in case of any dificulties Regards, MPS |
||||
| Google The UNIX and Linux Forums |