Re: Pure newbie :(
Re: Pure newbie :(
- Subject: Re: Pure newbie :(
- From: Ben Dougall <email@hidden>
- Date: Tue, 11 Nov 2003 22:14:19 +0000
On Tuesday, November 11, 2003, at 07:54 pm, David Blanton wrote:
On 11/11/03 12:07 PM, "Tony S. Wu" <email@hidden> wrote:
try using double.
never compare two floats.
Why never compare two floats?
you can compare but not like :
if( a == b ) {
...
that also applies to doubles. those number types go a bit haywire in
the smaller digits. so when you say:
float x = 4.0;
internally the computer will have x down as something like
4.0000000000238 believe it or not. and those inaccuracies vary so when
you compare literally like if(a == b) a does not equal b so far as the
computer's concerned. it's because base 2 (what computers use) is not
compatible with base 10. eg the number 1/3 cannot be accurately store
in base 10. 1/3 is 0.333333333333333333333etc.. it's not a problem with
objective-c or c or macs, but computers - all computers. even
calculators. apparently they semi-get round it by storing numbers
internally to a higher degree of accuracy that's displayed - so hides
the inaccuracy. do a search on google for something like "accuracy
double float" and you'll get a better more comprehensive explanation.
here's some c (easily converted to obj-c) i've used that compares
doubles or floats:
/* good way to compare two doubles for equality (or floats: use the
fabsf() function instead of fabs() )
with varying (up to you) accuracy - the epsilon value. 0.0001 or
0.00000001 for example. */
#include <stdio.h>
#include <math.h>
#define EPSILON 0.000001
main()
{
double a = 0.0;
double b = 0.0;
int i;
for (i = 0; i < 50; i++)
a += 0.01;
for (i = 0; i < 25; i++)
b += 0.02;
printf("%.30g\n%.30g\n", a, b);
if (fabs(a - .5) < EPSILON)
printf("smart test tests: EQUAL\n");
else
printf("smart test tests: NOT EQUAL\n");
}
_______________________________________________
cocoa-dev mailing list | email@hidden
Help/Unsubscribe/Archives:
http://www.lists.apple.com/mailman/listinfo/cocoa-dev
Do not post admin requests to the list. They will be ignored.