Re: float question

2006-01-23 Thread Peter Strömberg
On 23 Jan 2006 at 2:10, ramrunner wrote:

 why does the add loses a decimal point?
 again sorry if it's my mistake (probably) but i'm confused ;) .

What Every Computer Scientist Should Know About Floating-Point Arithmetic

http://docs.sun.com/source/806-3568/ncg_goldberg.html



float question

2006-01-22 Thread ramrunner
Hi , i am not sure if the following indicates a prob, if it does i
will issue a PR.
*sorry if i miss something here*
cosider the following: (obsd x86 3.8-current gcc version 3.3.5 (propolice))
float a;
int main()
{
for(;a3;a+=0.1)
printf(%f\n,a);
return 1;
}
output :
0.00
0.10

2.70
2.79
2.89
2.99
why does the add loses a decimal point?
again sorry if it's my mistake (probably) but i'm confused ;) .

please CC not in [EMAIL PROTECTED]
DsP



Re: float question

2006-01-22 Thread David Higgs
Floating point numbers aren't perfectly precise.

See http://c-faq.com/fp/

--david

On 1/22/06, ramrunner [EMAIL PROTECTED] wrote:
 Hi , i am not sure if the following indicates a prob, if it does i
 will issue a PR.
 *sorry if i miss something here*
 cosider the following: (obsd x86 3.8-current gcc version 3.3.5 (propolice))
 float a;
 int main()
 {
 for(;a3;a+=0.1)
 printf(%f\n,a);
 return 1;
 }
 output :
 0.00
 0.10
 
 2.70
 2.79
 2.89
 2.99
 why does the add loses a decimal point?
 again sorry if it's my mistake (probably) but i'm confused ;) .

 please CC not in [EMAIL PROTECTED]
 DsP



Re: float question

2006-01-22 Thread theo
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

ramrunner wrote:
 float a;
 int main()
 {
 for(;a3;a+=0.1)
 printf(%f\n,a);
 return 1;
 }
 output :
 0.00
 0.10
 
 2.70
 2.79
 2.89
 2.99
 why does the add loses a decimal point?


float is so tricky...
Never use it for precision.

For example :
float a,b; if(a==b) {} may fail.
if( abs(a-b)  0.1 ) {} may work.
You may want to look ceil(3) and floor(3) as well.


Using printf(%.2f\na) works for me. Error depends on the precision.

I would rather use something like that :
int main(void)
{
int a=0;
for(a=0; a30; a++)
printf(%f\n,a/10.); /* Do not forget the '.' */
/*or printf(%d.%d\n, a/10, a%10); depending on the
context. */
return 1;
}



cheers,
theo
Comment: Using GnuPG with Thunderbird - http://enigmail.mozdev.org

iD8DBQFD1Cq0SH6NzHMSyhIRAswgAJ9L6DvPZR03WF9VCQ3KAd+YsGlCVwCfcP9U
++cEzwTwb7Cxi3P7SdyWPIw=
=bjmn
-END PGP SIGNATURE-