digitalmars.D.learn - opCmp with double values
- kerdemdemir (29/29) Dec 24 2017 In documentation and forums I found some example for overloading
- =?UTF-8?Q?Ali_=c3=87ehreli?= (7/8) Dec 24 2017 I can't answer your question but I know that the comparison above is
In documentation and forums I found some example for overloading opCmp for int values. But I couldn't see any examples for double values. That is what I come up with my own: struct AdjustableVal ( T = double ) { this ( T initVal ) { curVal = initVal; initialVal = initVal; } int opCmp( T rhs ) const { auto diff = curVal - rhs; if ( fabs(diff) < 0.00000001 ) return 0; else if ( diff < 0 ) return -1; else return 1; } T curVal; T initialVal; } Do you guys see any problem with it or any suggestions? Secondly if the value type(T) does not have "-" operator, is it possible to still get my code compiled somehow with static_if? Erdem
Dec 24 2017
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
Dec 24 2017
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 AliI'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.
Dec 24 2017
25.12.2017 10:40, drug пишет:25.12.2017 09:50, Ali Çehreli пишет: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; } ```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 AliI'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.
Dec 24 2017