Module: AppMath::Basics
- Defined in:
- lib/appmath_basics.rb
Overview
A Module which collects simple utility functions.
Class Method Summary collapse
-
.cut(x) ⇒ Object
Returns the nearest number to x, which up to sign and power of 10 is one of the numbers in the array c in the function body.
-
.inf(a, b) ⇒ Object
Returns the smaller of the two numbers a and b.
-
.sign(a) ⇒ Object
Returns the sign of a as a real number.
-
.sign2(a, b) ⇒ Object
Returns ‘a with the sign of b’.
-
.sup(a, b) ⇒ Object
Returns the larger of the two numbers a and b.
Class Method Details
.cut(x) ⇒ Object
Returns the nearest number to x, which up to sign and power of 10 is one of the numbers in the array c in the function body. For instance,
c = [1,2,5,7.5,10]
In a sense, here cutting is a more drastic version of rounding. It will be used in order to create reasonable axis subdivsion in graphical representation of data.
86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 |
# File 'lib/appmath_basics.rb', line 86 def Basics.cut(x) fail "x is not a number" if x.nan? fail "x is not finite" if x.infinite? c = [R.c1,R.c2,R.c5,R.c(7.5),R.c10] return R.c0 if x.zero? s = Basics.sign(x) y1 = x.abs ylog = y1.log10 ylogInt = ylog.floor yMantisse = ylog - ylogInt y = R.c10 ** yMantisse fail "Basics.cut(): !(1 <= y)" if !(R.c1 <= y) fail "Basics.cut(): !(y < 10)" if !(y < R.c10) i = 0 while y > c[i] i += 1 end cd = c.length fail "unexpected failure in function Basics.cut" if i < 0 || i >= cd yu = c[i] # yu is the smallest c[k] which is larger or equal to y if i==0 yf = yu else fail "unexpected failure in function Basics.cut" if (i-1) < 0 || (i-1) >= cd yl = c[i-1] yf = yu-y <y -yl ? yu : yl # now yf is the c[k] which is nearest to y end return yf.ldexp(ylogInt) * s # sign and exponent are restored end |
.inf(a, b) ⇒ Object
Returns the smaller of the two numbers a and b.
58 59 60 |
# File 'lib/appmath_basics.rb', line 58 def Basics.inf(a, b) a < b ? a : b end |
.sign(a) ⇒ Object
Returns the sign of a as a real number.
63 64 65 66 67 68 69 70 71 |
# File 'lib/appmath_basics.rb', line 63 def Basics.sign(a) if a > R.c0 R.c1 elsif a < R.c0 -R.c1 else R.c0 end end |
.sign2(a, b) ⇒ Object
Returns ‘a with the sign of b’. Programming idiom frequently used in the ‘Numerical Recipes in C’ by Press et al.
75 76 77 |
# File 'lib/appmath_basics.rb', line 75 def Basics.sign2(a, b) b >= R.c0 ? a.abs : -a.abs end |
.sup(a, b) ⇒ Object
Returns the larger of the two numbers a and b.
53 54 55 |
# File 'lib/appmath_basics.rb', line 53 def Basics.sup(a, b) a <= b ? b : a end |