swarm-modeling
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

[Swarm-Modelling] possible problem comparing doubles


From: paul box
Subject: [Swarm-Modelling] possible problem comparing doubles
Date: Wed, 28 Feb 2007 15:32:07 +0930

Hello all

I'm having a problem with a simulation, where the culprit line seems
to be a comparison between doubles.

I'm describing shrimp migrating upstream from pool to pool.  In this
scenario, the only thing the shrimp wants is to find the least crowded
pool upstream (upstream pool with the lowest shrimp density). The pool
contains the following characteristics:

@interface Pool {
 ...
id <List> upstreamPoolList;  // any number of pools upstream
double shrimpDensity;  // number of shrimps / area
double area;               // pool surface area
id <List> shrimpList;

...
}



@implementation Pool {

...
-(double) getShrimpDensity {return shrimpDensity;}
- updateShrimpDensity {
 shrimpDensity = (double) [shrimpList getCount] / area;
 return self;
}

...
@end

The shrimp contains the following:

@interface Shrimp {

 Pool * myPool;  // the pool I'm currently inhabiting
}

@implelmentation Shrimp {

...
-step {
 [self moveToPool: [self findBestPool]];
 return self;
}

-findBestPool {
 Pool * aPool;
 Pool * bestPool;
 int i;

 bestPoool = myPool;

 for (i=0; i<[[myPool getUpstreaPools] getCount]; i++){
   aPool = [[myPool getUpstreamPools] atOffset: i];
  if ([aPool getShrimpDensity] < [bestPool getShrimpDensity])
   bestPool = aPool;
  }

 return bestPool;
}


This code was not producing results that made sense.  When I changed
the [getShrimpDensity] to the following, it works fine:

-(int) getShrimpDensity { return (int) (shrimpDensity * 100000);}

That changed the statement in [findBestPool ] to compare integers
instead of doubles.  I did not want to write the statement that way,
because I don't want to be concerned in this stage as to whether
100000 is an appropriate scaling number or not.

Is comparison of doubles in a logical statement a sin?  I have always
avoided testing for equality in doubles, but I had thought that simply
choosing the larger of two doubles a valid, if potentially sloppy,
operation.

The above code failed even when comparing doubles of several orders of
magnitude difference (e.g., 70.334 > 0.00135, or 70.334 > 0).

--
//////////////////////////
// Paul Box
// Alice Springs, NT  Australia
//


reply via email to

[Prev in Thread] Current Thread [Next in Thread]