opCmp with double values

drug drug2004 at bk.ru
Mon Dec 25 07:43:58 UTC 2017


25.12.2017 10:40, drug пишет:
> 25.12.2017 09:50, Ali Çehreli пишет:
>> On 12/24/2017 02:10 AM, kerdemdemir wrote:
>>
>>  >          if (  fabs(diff) < 0.00000001 )
>>
>> I can't answer your question but I know that the comparison above is 
>> wrong because it can be meaningful only if the values are sufficiently 
>> larger than that hard-coded value.
>>
>> I think feqrel() will be useful there:
>>
>>    https://dlang.org/phobos/std_math.html#.feqrel
>>
>> Ali
>>
> I'd do something like that (disclaimer - from memory):
> ```
>      int opCmp( T rhs ) const {
>          auto diff = curVal - rhs;
>      auto epsilon = max(curVal.epsilon, rhs.epsilon);
>          if (  fabs(diff) < epsilon )
>              return 0;
>          else if ( diff < 0 )
>              return -1;
>          else
>              return 1;
>      }
> ```
> so in this case epsilon is also floating.

should be
  ```
       int opCmp( T rhs ) const {
           auto diff = curVal - rhs;
           // get error for curVal and rhs
           auto epsilon = max(curVal.epsilon * curVal, rhs.epsilon * rhs);
           if (  fabs(diff) < epsilon )
               return 0;
           else if ( diff < 0 )
               return -1;
           else
               return 1;
       }
  ```


More information about the Digitalmars-d-learn mailing list