comparison SilverlightGlimpse/SilverFlow.Controls/Extensions/MathExtensions.cs @ 63:536498832a79

Latest version before changing bindings to Listbox
author Steven Hollidge <stevenhollidge@hotmail.com>
date Sun, 22 Apr 2012 13:33:42 +0100
parents
children
comparison
equal deleted inserted replaced
62:810116cd6b8e 63:536498832a79
1 using System;
2
3 namespace SilverFlow.Controls.Extensions
4 {
5 /// <summary>
6 /// Math extensions
7 /// </summary>
8 public static class MathExtensions
9 {
10 /// <summary>
11 /// Determines whether the number is NaN.
12 /// </summary>
13 /// <param name="number">The number.</param>
14 /// <returns>
15 /// <c>true</c> if is NaN; otherwise, <c>false</c>.
16 /// </returns>
17 public static bool IsNotSet(this double number)
18 {
19 return double.IsNaN(number);
20 }
21
22 /// <summary>
23 /// Determines whether the specified number is near the test number.
24 /// </summary>
25 /// <param name="number">The number.</param>
26 /// <param name="testNumber">The test number.</param>
27 /// <param name="accuracy">Accuracy.</param>
28 /// <returns>
29 /// <c>true</c> if the specified number is near the testing one; otherwise, <c>false</c>.
30 /// </returns>
31 public static bool IsNear(this double number, double testNumber, double accuracy)
32 {
33 return number >= (testNumber - accuracy) && number <= (testNumber + accuracy);
34 }
35
36 /// <summary>
37 /// Compares two numbers without their signs and gets absolutely minimal value.
38 /// </summary>
39 /// <param name="num1">First number.</param>
40 /// <param name="num2">Second number.</param>
41 /// <returns>Absolutely minimal value.</returns>
42 public static double AbsMin(double num1, double num2)
43 {
44 if (num1.IsNotSet() && num2.IsNotSet())
45 return double.NaN;
46
47 if (num1.IsNotSet()) return num2;
48 if (num2.IsNotSet()) return num1;
49
50 double abs1 = Math.Abs(num1);
51 double abs2 = Math.Abs(num2);
52
53 if (abs1 < abs2) return num1;
54 if (abs2 < abs1) return num2;
55
56 // Abs. values are equal. Return first number
57 return num1;
58 }
59
60 /// <summary>
61 /// Ensures the given number is in the specified range.
62 /// </summary>
63 /// <param name="number">The number.</param>
64 /// <param name="low">The lower limit.</param>
65 /// <param name="high">The upper limit.</param>
66 /// <returns>A number in the specified range.</returns>
67 public static double EnsureInRange(this double number, double low, double high)
68 {
69 if (number.IsNotSet()) return double.NaN;
70
71 double result = Math.Max(number, low);
72 return Math.Min(result, high);
73 }
74
75 /// <summary>
76 /// Returns a double value if it is not a NAN, or zero.
77 /// </summary>
78 /// <param name="number">The number.</param>
79 /// <returns>Double value if it is not a NAN, or zero.</returns>
80 public static double ValueOrZero(this double number)
81 {
82 return double.IsNaN(number) ? 0 : number;
83 }
84 }
85 }