Class: Fit::ScientificDouble
- Inherits:
-
Object
- Object
- Fit::ScientificDouble
- Defined in:
- lib/fit/scientific_double.rb
Overview
Warning: not (yet) a general number usable in all calculations
Instance Attribute Summary collapse
-
#precision ⇒ Object
Returns the value of attribute precision.
Class Method Summary collapse
Instance Method Summary collapse
- #<=>(obj) ⇒ Object
- #==(obj) ⇒ Object
-
#initialize(value) ⇒ ScientificDouble
constructor
A new instance of ScientificDouble.
-
#nan? ⇒ Boolean
unused?.
- #to_f ⇒ Object
- #to_s ⇒ Object
Constructor Details
#initialize(value) ⇒ ScientificDouble
Returns a new instance of ScientificDouble.
11 12 13 14 |
# File 'lib/fit/scientific_double.rb', line 11 def initialize value @value = Float(value) @precision = 0 end |
Instance Attribute Details
#precision ⇒ Object
Returns the value of attribute precision.
9 10 11 |
# File 'lib/fit/scientific_double.rb', line 9 def precision @precision end |
Class Method Details
.precision(s) ⇒ Object
26 27 28 29 30 |
# File 'lib/fit/scientific_double.rb', line 26 def ScientificDouble.precision s value = s.to_f bound = tweak(s.strip).to_f (bound - value).abs end |
.tweak(s) ⇒ Object
32 33 34 35 36 37 38 39 40 41 |
# File 'lib/fit/scientific_double.rb', line 32 def ScientificDouble.tweak s pos = s.downcase.index('e') unless pos.nil? return tweak(s[0..(pos - 1)]) + s[pos..-1] end unless s.index('.').nil? return s + "5" end return s + ".5" end |
.value_of(s) ⇒ Object
16 17 18 19 20 21 22 23 24 |
# File 'lib/fit/scientific_double.rb', line 16 def ScientificDouble.value_of s if s.downcase.index('infinity') new (1.0/0.0) # Infinity else result = new s.to_f result.precision = precision s result end end |
Instance Method Details
#<=>(obj) ⇒ Object
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
# File 'lib/fit/scientific_double.rb', line 48 def <=> obj other = obj.to_f diff = @value - other # workaround the much more precise way of Ruby doing floats than Java return 0 if @precision.zero? and diff.abs < 1.0e-5 precision = @precision > obj.precision ? @precision : obj.precision return -1 if diff < -precision return 1 if diff > precision return 0 if @value.nan? and other.nan? return 1 if @value.nan? return -1 if other.nan? 0 end |
#==(obj) ⇒ Object
43 44 45 46 |
# File 'lib/fit/scientific_double.rb', line 43 def == obj sd = ScientificDouble.value_of obj.to_s self.<=>(sd) == 0 end |
#nan? ⇒ Boolean
unused?
64 |
# File 'lib/fit/scientific_double.rb', line 64 def nan?; @value.nan?; end |
#to_f ⇒ Object
65 |
# File 'lib/fit/scientific_double.rb', line 65 def to_f; @value; end |
#to_s ⇒ Object
66 |
# File 'lib/fit/scientific_double.rb', line 66 def to_s; @value.to_s; end |