瀏覽代碼

cmMath.h/c : Added cmIsCloseX().

master
Kevin Larke 9 年之前
父節點
當前提交
91c88a4ec7
共有 2 個檔案被更改,包括 55 行新增0 行删除
  1. 48
    0
      cmMath.c
  2. 7
    0
      cmMath.h

+ 48
- 0
cmMath.c 查看文件

@@ -419,3 +419,51 @@ double   cmRandDouble( double min, double max )
419 419
   double offs = max - min;
420 420
   return min + cmMax(0,cmMin(offs,(offs * (double)rand() / RAND_MAX)));
421 421
 }
422
+
423
+
424
+//=================================================================
425
+// Base on: http://stackoverflow.com/questions/3874627/floating-point-comparison-functions-for-c-sharp
426
+
427
+bool cmIsCloseD( double x0, double x1, double eps )
428
+{
429
+  double d = fabs(x0-x1);
430
+  
431
+  if( x0 == x1 )
432
+    return true;
433
+
434
+  if( x0==0 || x1==0 || d<DBL_MIN )
435
+    return d < (eps * DBL_MIN);
436
+
437
+  return (d / cmMin( fabs(x0) + fabs(x1), DBL_MAX)) < eps;
438
+}
439
+
440
+bool cmIsCloseF( float  x0, float  x1, double  eps_d )
441
+{
442
+  float eps = (float)eps_d;
443
+  float d = fabsf(x0-x1);
444
+  
445
+  if( x0 == x1 )
446
+    return true;
447
+
448
+  if( x0==0 || x1==0 || d<FLT_MIN )
449
+    return d < (eps * FLT_MIN);
450
+
451
+  return (d / cmMin( fabsf(x0) + fabsf(x1), FLT_MAX)) < eps;
452
+}
453
+
454
+bool cmIsCloseI( int x0, int x1, double eps )
455
+{
456
+  if( x0 == x1 )
457
+    return true;
458
+  
459
+  return abs(x0-x1)/(abs(x0)+abs(x1)) < eps;
460
+}
461
+
462
+
463
+bool cmIsCloseU( unsigned x0, unsigned x1, double eps )
464
+{
465
+  if( x0 == x1 )
466
+    return true;
467
+  
468
+  return abs(x0-x1)/(x0+x1) < eps;
469
+}

+ 7
- 0
cmMath.h 查看文件

@@ -67,4 +67,11 @@ int      cmRandInt( int min, int max );
67 67
 unsigned cmRandUInt( unsigned min, unsigned max );
68 68
 float    cmRandFloat( float min, float max );
69 69
 double   cmRandDouble( double min, double max );
70
+
71
+//=================================================================
72
+bool cmIsCloseD( double   x0, double   x1, double eps );
73
+bool cmIsCloseF( float    x0, float    x1, double eps );
74
+bool cmIsCloseI( int      x0, int      x1, double eps );
75
+bool cmIsCloseU( unsigned x0, unsigned x1, double eps );
76
+
70 77
 #endif

Loading…
取消
儲存