flt 1.5.0 → 1.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. checksums.yaml +4 -4
  2. data/History.txt +8 -0
  3. data/README.md +765 -0
  4. data/expand.rb +2 -0
  5. data/flt.gemspec +1 -0
  6. data/lib/flt.rb +1 -1
  7. data/lib/flt/bigdecimal.rb +2 -5
  8. data/lib/flt/bin_num.rb +1 -4
  9. data/lib/flt/complex.rb +10 -9
  10. data/lib/flt/dec_num.rb +9 -10
  11. data/lib/flt/float.rb +4 -6
  12. data/lib/flt/math.rb +3 -4
  13. data/lib/flt/num.rb +54 -21
  14. data/lib/flt/sugar.rb +1 -2
  15. data/lib/flt/support.rb +5 -2
  16. data/lib/flt/support/flag_values.rb +1 -1
  17. data/lib/flt/support/rationalizer.rb +3 -3
  18. data/lib/flt/support/rationalizer_extra.rb +6 -6
  19. data/lib/flt/support/reader.rb +1 -1
  20. data/lib/flt/tolerance.rb +2 -7
  21. data/lib/flt/trigonometry.rb +0 -2
  22. data/lib/flt/version.rb +1 -1
  23. data/setup.rb +1 -2
  24. data/test/generate_trig_data.rb +6 -6
  25. data/test/helper.rb +11 -5
  26. data/test/reader.rb +1 -1
  27. data/test/test_base_digits.rb +4 -2
  28. data/test/test_basic.rb +7 -7
  29. data/test/test_big_decimal.rb +21 -21
  30. data/test/test_bin.rb +1 -1
  31. data/test/test_bin_arithmetic.rb +1 -1
  32. data/test/test_binfloat_conversion.rb +1 -1
  33. data/test/test_coercion.rb +1 -1
  34. data/test/test_comparisons.rb +4 -4
  35. data/test/test_dectest.rb +2 -2
  36. data/test/test_define_conversions.rb +10 -10
  37. data/test/test_epsilon.rb +1 -1
  38. data/test/test_exact.rb +12 -11
  39. data/test/test_flags.rb +1 -1
  40. data/test/test_float.rb +23 -25
  41. data/test/test_format.rb +1 -1
  42. data/test/test_formatter.rb +6 -8
  43. data/test/test_hex_format.rb +2 -2
  44. data/test/test_multithreading.rb +1 -1
  45. data/test/test_normalized.rb +1 -1
  46. data/test/test_num_constructor.rb +6 -1
  47. data/test/test_odd_even.rb +1 -1
  48. data/test/test_rationalizer.rb +1 -1
  49. data/test/test_round.rb +36 -1
  50. data/test/test_sugar.rb +6 -6
  51. data/test/test_to_int.rb +4 -4
  52. data/test/test_to_rf.rb +126 -1
  53. data/test/test_tol.rb +1 -1
  54. data/test/test_trig.rb +1 -1
  55. data/test/test_ulp.rb +3 -3
  56. metadata +18 -4
  57. data/README.rdoc +0 -614
@@ -1,6 +1,6 @@
1
1
  require File.expand_path(File.join(File.dirname(__FILE__),'helper.rb'))
2
2
 
3
- class TestTolerance < Test::Unit::TestCase
3
+ class TestTolerance < Minitest::Test
4
4
 
5
5
 
6
6
  def setup
@@ -1,7 +1,7 @@
1
1
  require File.expand_path(File.join(File.dirname(__FILE__),'helper.rb'))
2
2
  require File.dirname(__FILE__) + '/../lib/flt/math'
3
3
 
4
- class TestTrig < Test::Unit::TestCase
4
+ class TestTrig < Minitest::Test
5
5
 
6
6
 
7
7
  def setup
@@ -1,6 +1,6 @@
1
1
  require File.expand_path(File.join(File.dirname(__FILE__),'helper.rb'))
2
2
 
3
- class TestUlp < Test::Unit::TestCase
3
+ class TestUlp < Minitest::Test
4
4
 
5
5
 
6
6
  def setup
@@ -67,7 +67,7 @@ class TestUlp < Test::Unit::TestCase
67
67
  DecNum.context.exact = true
68
68
  assert DecNum(1).ulp.nan?, "No ulps can be computed in exact contexts"
69
69
  DecNum.context.traps[DecNum::InvalidOperation] = true
70
- assert_raise(DecNum::InvalidOperation) { DecNum(1).ulp }
70
+ assert_raises(DecNum::InvalidOperation) { DecNum(1).ulp }
71
71
 
72
72
  end
73
73
 
@@ -119,7 +119,7 @@ class TestUlp < Test::Unit::TestCase
119
119
  BinNum.context.exact = true
120
120
  assert BinNum(1).ulp.nan?, "No ulps can be computed in exact contexts"
121
121
  BinNum.context.traps[BinNum::InvalidOperation] = true
122
- assert_raise(BinNum::InvalidOperation) { BinNum(1).ulp }
122
+ assert_raises(BinNum::InvalidOperation) { BinNum(1).ulp }
123
123
 
124
124
  end
125
125
 
metadata CHANGED
@@ -1,14 +1,14 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: flt
3
3
  version: !ruby/object:Gem::Version
4
- version: 1.5.0
4
+ version: 1.5.1
5
5
  platform: ruby
6
6
  authors:
7
7
  - Javier Goizueta
8
8
  autorequire:
9
9
  bindir: bin
10
10
  cert_chain: []
11
- date: 2015-04-06 00:00:00.000000000 Z
11
+ date: 2017-03-04 00:00:00.000000000 Z
12
12
  dependencies:
13
13
  - !ruby/object:Gem::Dependency
14
14
  name: bundler
@@ -38,6 +38,20 @@ dependencies:
38
38
  - - ">="
39
39
  - !ruby/object:Gem::Version
40
40
  version: '0'
41
+ - !ruby/object:Gem::Dependency
42
+ name: minitest
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: '5.10'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: '5.10'
41
55
  description: Decimal and binary arbitrary precision floating point numbers in pure
42
56
  Ruby.
43
57
  email:
@@ -50,7 +64,7 @@ files:
50
64
  - Gemfile
51
65
  - History.txt
52
66
  - License.txt
53
- - README.rdoc
67
+ - README.md
54
68
  - Rakefile
55
69
  - expand.rb
56
70
  - flt.gemspec
@@ -130,7 +144,7 @@ required_rubygems_version: !ruby/object:Gem::Requirement
130
144
  version: '0'
131
145
  requirements: []
132
146
  rubyforge_project:
133
- rubygems_version: 2.2.2
147
+ rubygems_version: 2.6.8
134
148
  signing_key:
135
149
  specification_version: 4
136
150
  summary: Floating Point Numbers
@@ -1,614 +0,0 @@
1
- = Introduction
2
- {<img src="https://badge.fury.io/rb/flt.svg" alt="Gem Version" />}[http://badge.fury.io/rb/flt]
3
- {<img src="https://travis-ci.org/jgoizueta/flt.svg?branch=master" alt="Build tests" />}[https://travis-ci.org/jgoizueta/flt]
4
-
5
- This library provides arbitrary precision floating-point types for Ruby. All types and
6
- functions are within a namespace called Flt. Decimal and Binary floating point numbers
7
- are implemented in classes Flt::DecNum and Flt::BinNum. These types are completely
8
- written in Ruby using the multiple precision native integers. The performance
9
- could be improved in the future by using a C extension based on the decNumber libray.
10
-
11
- The Flt::Tolerance classes and the Flt.Tolerance() constructor handle floating point
12
- tolerances defined in flexible ways.
13
-
14
- Context classes are defined in the files
15
- flt/float.rb[link:lib/flt/float_rb.html] and
16
- flt/bigdecimal.rb[link:lib/flt/bigdecimal_rb.html]
17
- for Float and BigDecimal numbers that aid to the interchangeability of floating point types. This
18
- represent the only definition of identifiers outside the Flt namespace: the methods
19
- Float.context() and BigDecimal.context() and some contants in Float.
20
-
21
- This library is the successor of the ruby-decimal gem, that defined the Decimal class
22
- for decimal floating point; that class has been renamed to Flt::DecNum and support
23
- has been added for binary floating point and tolerances.
24
-
25
- The documentation for this package is available at http://rdoc.info/github/jgoizueta/flt/frames
26
-
27
- The code is at http://github.com/jgoizueta/flt/
28
-
29
- = DecNum
30
-
31
- Flt::DecNum is a standards-compliant arbitrary precision decimal floating-point type for Ruby.
32
- It is based on the Python Decimal class.
33
-
34
- == Standars compliance.
35
-
36
- DecNum is designed to be conformant to the General Decimal Arithmetic Specification
37
- and the revised IEEE 754 standard (IEEE 754-2008).
38
-
39
- = Examples of use
40
-
41
- To install the library use gem from the command line:
42
-
43
- gem install flt
44
-
45
- Then require the library in your code (if it fails you may need to <tt>require 'rubygems'</tt> first)
46
- require 'flt'
47
- include Flt
48
-
49
- Now we can use the DecNum class simply like this:
50
-
51
- puts DecNum(1)/DecNum(3) # -> 0.3333333333333333333333333333
52
-
53
- DecNum() is a constructor that can be used instead of DecNum.new()
54
-
55
- == Contexts
56
-
57
- Contexts are environments for arithmetic operations. They govern precision, set rules
58
- for rounding, determine which signals are treated as exceptions, and limit the range
59
- for exponents.
60
-
61
- Each thread has an active context that can be accessed like this:
62
-
63
- puts DecNum.context.precision # -> 28
64
-
65
- The active context can be modified globally for the current thread:
66
-
67
- DecNum.context.precision = 2
68
- puts DecNum.context.precision # -> 2
69
- puts DecNum(1)/DecNum(3) # -> 0.33
70
- DecNum.context.precision += 7
71
- puts DecNum.context.precision # -> 9
72
- puts DecNum(1)/DecNum(3) # -> 0.333333333
73
-
74
- Or it can be altered locally inside a block:
75
-
76
- DecNum.context do
77
- DecNum.context.precision = 5
78
- puts DecNum.context.precision # -> 5
79
- end
80
- puts DecNum.context.precision # -> 9
81
-
82
- The block for a local context can be passed the current context as an argument:
83
-
84
- DecNum.context do |local_context|
85
- local_context.precision = 5
86
- puts DecNum.context.precision # -> 5
87
- end
88
- puts DecNum.context.precision # -> 9
89
-
90
- A context object can also be used to define the local context:
91
-
92
- my_context = DecNum::Context(:precision=>20)
93
- DecNum.context(my_context) do |context|
94
- puts context.precision
95
- end # -> 20
96
-
97
- And individual parameters can be assigned like this:
98
-
99
- puts DecNum.context.precision # -> 9
100
- puts DecNum.context.rounding # -> half_even
101
- DecNum.context(:rounding=>:down) do |context|
102
- puts context.precision # -> 9
103
- puts context.rounding # -> down
104
- end
105
-
106
- Contexts created with the DecNum::Context() constructor
107
- inherit from DecNum::DefaultContext.
108
- Default context attributes can be established by modifying
109
- that object:
110
-
111
- DecNum::DefaultContext.precision = 10
112
- DecNum.context = DecNum::Context(:rounding=>:half_up)
113
- puts DecNum.context.precision # -> 10
114
-
115
- Note that a context object assigned to DecNum.context is copied,
116
- so it is not altered through DecNum.context:
117
-
118
- puts my_context.precision # -> 20
119
- DecNum.context = my_context
120
- DecNum.context.precision = 2
121
- puts my_context.precision # -> 20
122
-
123
- So, DefaultContext is not altered when modifying DecNum.context.
124
-
125
- Methods that use a context have an optional parameter to override
126
- the active context (DecNum.context) :
127
-
128
- DecNum.context.precision = 3
129
- puts DecNum(1).divide(3) # -> 0.333
130
- puts DecNum(1).divide(3, my_context) # -> 0.33333333333333333333
131
-
132
- Individual context parameters can also be overriden:
133
-
134
- puts DecNum(1).divide(3, :precision=>6) # -> 0.333333
135
-
136
- There are two additional predefined contexts DecNum::ExtendedContext
137
- and DecNum::BasicContext that are not meant to be modified; they
138
- can be used to achieve reproducible results. We will use
139
- DecNum::ExtendedContext in the following examples:
140
-
141
- DecNum.context = DecNum::ExtendedContext
142
-
143
- Most decimal operations can be executed by using either Context or DecNum methods:
144
-
145
- puts DecNum.context.exp(1) # -> 2.71828183
146
- puts DecNum(1).exp # -> 2.71828183
147
-
148
- If using Context methods, values are automatically converted as if the DecNum() constructor
149
- was used.
150
-
151
- ==Rounding
152
-
153
- Results are normally rounded using the precision (number of significant digits)
154
- and rounding mode defined in the context.
155
-
156
- DecNum.context.precision = 4
157
- puts DecNum(1)/DecNum(3) # -> 0.3333
158
- puts DecNum('1E20')-DecNum('1E-20') # -> 1.000E+20
159
- DecNum.context.rounding = :half_up
160
- puts +DecNum('100.05') # -> 100.1
161
- DecNum.context.rounding = :half_even
162
- puts +DecNum('100.05') # -> 100.0
163
-
164
- Note that input values are not rounded, only results; we use
165
- the plus operator to force rounding here:
166
-
167
- DecNum.context.precision = 4
168
- x = DecNum('123.45678')
169
- puts x # -> 123.45678
170
- puts +x # -> 123.5
171
-
172
- Precision can be also set to 'exact' to avoid rounding, by using
173
- the exact property or using a 0 precision. In exact mode results
174
- are never rounded and results that have an infinite number of
175
- digits trigger the DecNum::Inexact exception.
176
-
177
- DecNum.context.exact = true
178
- puts DecNum('1E20')-DecNum('1E-20') # -> 99999999999999999999.99999999999999999999
179
- puts DecNum(16).sqrt # -> 4
180
- puts DecNum(16)/DecNum(4) # -> 4
181
- puts DecNum(1)/DecNum(3) # -> Exception : Flt::Num::Inexact
182
-
183
- DecNum.context.precision = 5
184
- puts DecNum('1E20')-DecNum('1E-20') # -> 1.0000E+20
185
- puts DecNum(16).sqrt # -> 4
186
- puts DecNum(16)/DecNum(4) # -> 4
187
- puts DecNum(1)/DecNum(3) # -> 0.33333
188
-
189
- There are also some methods for explicit rounding that provide
190
- an interface compatible with that of the Ruby Float class:
191
-
192
- puts DecNum('101.5').round # -> 102
193
- puts DecNum('101.5').round(0) # -> 102
194
- puts DecNum('101.12345').round(2) # -> 101.12
195
- puts DecNum('101.12345').round(-1) # -> 1.0E+2
196
- puts DecNum('101.12345').round(:places=>2) # -> 101.12
197
- puts DecNum('101.12345').round(:precision=>2) # -> 1.0E+2
198
- puts DecNum('101.5').round(:rounding=>:half_up) # -> 102
199
- puts DecNum('101.5').ceil # -> 102
200
- puts DecNum('101.5').floor # -> 101
201
- puts DecNum('101.5').truncate # -> 101
202
-
203
- ==Special values
204
-
205
- In addition to finite numbers, a DecNum object can represent some special values:
206
- * Infinity (+Infinity, -Infinity). The method DecNum#infinite? returns true for these to values.
207
- DecNum.infinity DecNum.infinity(-1) can be used to get these values.
208
- * NaN (not a number) represents undefined results. The method DecNum#nan? returns true for it and
209
- DecNum.nan can be used to obtain it. There is a variant, sNaN (signaling NaN) that causes
210
- an invalid operation condition if used; it can be detected with DecNum.snan?.
211
- A NaN can also include diagnostic information in its sign and coefficient.
212
-
213
- Any of the special values can be detected with DecNum#special?
214
- Finite numbers can be clasified with
215
- these methods:
216
- * DecNum#zero? detects a zero value (note that there are two zero values: +0 and -0)
217
- * DecNum#normal? detects normal values: those whose adjusted exponents are not less than @emin@.
218
- * DecNum#subnormal? detects subnormal values: those whose adjusted exponents are less than @emin@.
219
-
220
- ==Exceptions
221
-
222
- Exceptional conditions that may arise during operations have corresponding classes that represent them:
223
- * DecNum::InvalidOperation
224
- * DecNum::DivisionByZero
225
- * DecNum::DivisionImpossible
226
- * DecNum::DivisionUndefined
227
- * DecNum::Inexact
228
- * DecNum::Overflow
229
- * DecNum::Underflow
230
- * DecNum::Clamped
231
- * DecNum::InvalidContext
232
- * DecNum::Rounded
233
- * DecNum::Subnormal
234
- * DecNum::ConversionSyntax
235
-
236
- For each condition, a flag and a trap (boolean values) exist in the context.
237
- When a condition occurs, the corresponding flag in the context takes the value true (and remains
238
- set until cleared) and a exception is raised if the corresponding trap has the value true.
239
-
240
- DecNum.context.traps[DecNum::DivisionByZero] = false
241
- DecNum.context.flags[DecNum::DivisionByZero] = false
242
- puts DecNum(1)/DecNum(0) # -> Infinity
243
- puts DecNum.context.flags[DecNum::DivisionByZero] # -> true
244
- DecNum.context.traps[DecNum::DivisionByZero] = true
245
- puts DecNum(1)/DecNum(0) # -> Exception : Flt::Num::DivisionByZero
246
-
247
- ==Numerical conversion
248
-
249
- By default, DecNum is interoperable with Integer and Rational.
250
- Conversion happens automatically to operands:
251
-
252
- puts DecNum('0.1') + 1 # -> 1.1
253
- puts 7 + DecNum('0.2') # -> 7.2
254
- puts Rational(5,2) + DecNum('3') # -> 5.5
255
-
256
- Conversion can also be done explicitely with
257
- the DecNum constructor:
258
-
259
- puts DecNum(7) # -> 7
260
- puts DecNum(Rational(1,10)) # -> 0.1
261
-
262
- Converting a DecNum to other numerical types can be done with specific Ruby-style methods.
263
-
264
- puts DecNum('1.1').to_i # -> 1
265
- puts DecNum('1.1').to_r # -> 11/10
266
-
267
- (note the truncated result of to_i)
268
- Or with a generic method:
269
- puts DecNum('1.1').convert_to(Integer) # -> 1
270
- puts DecNum('1.1').convert_to(Rational) # -> 11/10
271
-
272
- Thera are also GDAS style conversion operations:
273
-
274
- puts DecNum('1.1').to_integral_value # -> 1
275
-
276
- And conversion is also possible to Float:
277
- puts DecNum('1.1').to_f # -> 1.1
278
- puts DecNum('1.1').convert_to(Float) # -> 1.1
279
- puts Float(DecNum('1.1')) # -> 1.1
280
-
281
- Types with predefined bidirectional conversion (Integer and Rational)
282
- can be operated with DecNum on either side of an operator, and the result will be a DecNum.
283
- For Float there is no predefined bidirectional conversion (see below how to define it)
284
- and the result of an operation between DecNum and Float will be of type Float.
285
-
286
- puts (DecNum('1.1') + 2.0).class # -> Float
287
- puts (2.0 + DecNum('1.1')).class # -> Float
288
-
289
- The conversion system is extensible. For example, we can include BigDecimal into it
290
- by defining suitable conversion procedures:
291
-
292
- DecNum.context.define_conversion_from(BigDecimal) do |x, context|
293
- DecNum(x.to_s)
294
- end
295
- DecNum.context.define_conversion_to(BigDecimal) do |x|
296
- BigDecimal.new(x.to_s)
297
- end
298
-
299
- Now we can mix BigDecimals and Decimals in expressions and convert from DecNum
300
- to BigDecimal:
301
-
302
- puts BigDecimal.new('1.1') + DecNum('2.2') # -> 3.3
303
- puts DecNum('1.1').convert_to(BigDecimal) # -> 0.11E1
304
-
305
- Note that the conversions are defined in a Context object and will be available only
306
- when that context applies. That way we can define conversions for specific purposes
307
- without affecting a program globally.
308
-
309
- As another example consider conversion from Float to DecNum, which is not defined by
310
- default because it can be defined in different ways depending on the purpose.
311
-
312
- A Float constant such as 0.1 defines a Float object which has a numerical value close to,
313
- but not exactly 1/10. When converting that Float to DecNum we could decide to preserve
314
- the exact numerical value of the number or try to find a simple decimal expression within
315
- a given tolerance. If we take the first approach we can define this conversion:
316
-
317
- DecNum.context.define_conversion_from(Float) do |x, context|
318
- s,e = Math.frexp(x)
319
- s = Math.ldexp(s, Float::MANT_DIG).to_i
320
- e -= Float::MANT_DIG
321
- DecNum(s*(Float::RADIX**e))
322
- end
323
-
324
- Note that the conversion we've defined depends on the context precision:
325
-
326
- DecNum.local_context(:precision=>20) { puts DecNum(0.1) } # -> 0.10000000000000000555
327
-
328
- DecNum.local_context(:precision=>12) { puts DecNum(0.1) } # -> 0.100000000000
329
-
330
- DecNum.local_context(:exact=>true) { puts DecNum(0.1) } # -> 0.1000000000000000055511151231257827021181583404541015625
331
-
332
- A different approach for Float to DecNum conversion is to find the shortest (fewer digits) DecNum
333
- that rounds to the Float with the binary precision that the Float has.
334
- We will assume that the DecNum to Float conversion done with the rounding mode of the DecNum context.
335
- The BinNum class has a method to perform this kind of conversion, so we will use it.
336
-
337
- DecNum.context.define_conversion_from(Float) do |x, dec_context|
338
- BinNum.context(:rounding=>dec_context.rounding) do |bin_context|
339
- BinNum(x).to_decimal
340
- end
341
- end
342
-
343
- The result is independent of the context precision.
344
-
345
- puts DecNum(0.1) # -> 0.1
346
- puts DecNum(1.0/3) # -> 0.3333333333333333
347
-
348
- This conversion gives the results expected most of the time, but it must be noticed that
349
- there must be some compromise, because different decimal literals convert to the same Float value:
350
-
351
- puts DecNum(0.10000000000000001) # -> 0.1
352
-
353
- There's also some uncertainty because the way the Ruby interpreter parses Float literals
354
- may not be well specified; in the usual case (IEEE Double Floats and round-to-even)
355
- the results will be as expected (correctly rounded Floats), but some platforms may
356
- behave differently.
357
-
358
- The BinNum also a instance method +to_decimal_exact+ to perform the previous 'exact' conversion, that
359
- could have be written:
360
-
361
- DecNum.context.define_conversion_from(Float) do |x, context|
362
- DecNum.context(context) do
363
- BinNum(x).to_decimal_exact
364
- end
365
- end
366
-
367
- == Abbreviation
368
-
369
- The use of DecNum can be made less verbose by requiring:
370
-
371
- require 'flt/d'
372
-
373
- This file defines +D+ as a synonym for +DecNum+:
374
-
375
- D.context.precision = 3
376
- puts +D('1.234') # -> 1.23
377
-
378
- Some convenient methods are added to numeric classes by requiring the optional
379
- flt/sugar.rb[link:lib/flt/sugar_rb.html]. This must be explicitely required
380
- because it could cause conflicts with other extensions of these classes.
381
-
382
- require 'flt/sugar'
383
-
384
- puts 34.odd? # -> false
385
- puts 34.even? # -> true
386
- puts 0.1.split.inspect # -> [1, 7205759403792794, -56]
387
- puts (-0.1).sign # -> -1
388
-
389
- A shortcut notation for DecNum is defined in this file (based on an idea by coderrr[http://coderrr.wordpress.com]
390
- which allows exact definitions with almost literal decimal syntax (note the underscore after the dot.)
391
-
392
- puts 10._123456789123456789 # -> 10.123456789123456789
393
-
394
- Additional underscores can be used to separate digits at any place except before the decimal point:
395
-
396
- puts 100_000._000_001 # -> 100000.000001
397
- puts 100_000._000_001.class # -> Flt::DecNum
398
-
399
- But note that 100_000.000_001 is a valid Float (it's not a DecNum because there isn't an underscore just after the
400
- decimal point):
401
-
402
- puts 100_000.000_001 # -> 100000.000001
403
- puts 100_000.000_001.class # -> Float
404
-
405
- There's also one important caveat with this notation: negative numbers with a zero integral part must be
406
- parenthesed (otherwise the minus has no effect because it affects only the null integer part):
407
-
408
- puts -0._5 # -> 0.5
409
- puts -(0._5) # -> -0.5
410
-
411
- == Error analysis
412
-
413
- The DecNum#ulp() method returns the value of a "unit in the last place" for a given number under
414
- the current context.
415
-
416
- D.context.precision = 4
417
- puts D('1.5').ulp # -> 0.001
418
- puts D('1.5E10').ulp # -> 1E+7
419
-
420
- Whe can compute the error in ulps of an approximation +aprx+ to correclty rounded value +exct+ with:
421
-
422
- def ulps(exct, aprx)
423
- (aprx-exct).abs/exct.ulp
424
- end
425
-
426
- puts ulps(DecNum('0.5000'), DecNum('0.5003')) # -> 3
427
- puts ulps(DecNum('0.5000'), DecNum('0.4997')) # -> 3
428
-
429
- puts ulps(DecNum('0.1000'), DecNum('0.1003')) # -> 3E+1
430
- puts ulps(DecNum('0.1000'), DecNum('0.0997')) # -> 3E+1
431
-
432
- puts ulps(DecNum(1), DecNum(10).next_minus) # -> 8.999E+4
433
- puts ulps(DecNum(1), DecNum(10).next_plus) # -> 9.01E+4
434
-
435
- Note that in the definition of ulps we use exct.ulp. If we had use aprx.ulp DecNum(10).next_plus
436
- would seem to be a better approximation to DecNum(1) than DecNum(10).next_minus. (Admittedly,
437
- such bad approximations should not be common.)
438
-
439
- == BinNum Input/Output
440
-
441
- BinNum can be defined with a decimal string literal and converted to one with to_s, as DecNum,
442
- but since this involves a change of base these are inexact operations subject to some specific precision limits.
443
-
444
- If we define the number with a binary literal, no base conversion is involved and the result is exactly defined;
445
- here we define a number with just one bit of precision:
446
-
447
- x = BinNum('0.001', :base=>2)
448
- puts x.number_of_digits # -> 1
449
- puts x.to_s(:base=>2) # -> 0.001
450
-
451
- Note that we could have defined it with more precision, e.g.
452
-
453
- y = BinNum('0.001000', :base=>2)
454
- puts y.number_of_digits # -> 4
455
- puts y.to_s(:base=>2) # -> 0.001000
456
-
457
- But let's get back to our one bit quantity, x, and convert it to a decimal string. Since the internal precision
458
- is only one bit it contains very little information:
459
-
460
- puts x # -> 0.1
461
-
462
- We can obtain more digits with the :all_digits option which show all the decimal digits that are significative
463
- for the given precision of 1 bit:
464
-
465
- puts x.to_s(:all_digits=>true) # -> 0.12
466
-
467
- We can also obtain the exact value of x by using the Num.convert_exact method to convert it to decimal (base 10):
468
-
469
- puts Num.convert_exact(x,10) # -> 0.125
470
-
471
- Let's convert the default decimal output back to another BinNum which will preserve its precision:
472
-
473
- y = BinNum(x.to_s)
474
-
475
- The result may seem ok:
476
-
477
- puts y # -> 0.1
478
-
479
- But is not exactly what we originally had:
480
-
481
- puts y==x # -> false
482
- puts y # -> 0.1
483
- puts y.number_of_digits # -> 5
484
- puts y.to_s(:base=>2) # -> 0.00011010
485
-
486
- The new value y has gained some digits because of the intermediate conversion to decimal: one decimal digit
487
- contains more information than one bit, and the result shows that.
488
-
489
- If we wanted to preserve exactly the number we should have done this:
490
-
491
- y = BinNum(x.to_s, :fixed, :precision=>x.number_of_digits)
492
- puts y==x # -> true
493
-
494
- To preserve the value we had to explicitly determine how many bits should y have.
495
-
496
- With the :fixed options the number produced by BinNum is rounded to the context precision (which can be
497
- overriden as in the example by other options):
498
-
499
- puts BinNum(x.to_s, :fixed, :precision=>32).to_s(:base=>2) # -> 0.00011001100110011001100110011001101
500
- puts BinNum(x.to_s, :fixed, :precision=>1).to_s(:base=>2) # -> 0.001
501
-
502
- Note also that if we normalize a value we will change it's precision to that of the context:
503
-
504
- puts x.number_of_digits # -> 1
505
- puts x.normalize.number_of_digits # -> 53
506
- puts x.normalize.to_s # -> 0.125
507
-
508
- == Mathematical functions
509
-
510
- There are two mathematical functions modules analogous to Ruby's Math for Float,
511
- Flt::DecNum::Math and Flt::BinNum::Math.
512
- Currently they consist of basic trigonometric functions, including hypot, logarithms and the exponential
513
- function, and the constants e and pi.
514
-
515
- Its functions can be accessed in a number of ways:
516
-
517
- require 'flt/math'
518
- DecNum.context(:precision=>10) do |context|
519
- # As module functions, using the current context for the enclosing Num class:
520
- puts DecNum::Math.sin(1)*DecNum::Math.pi # -> 2.643559064
521
- # As functions of a context object:
522
- puts context.sin(1)*context.pi # -> 2.643559064
523
- # Through a math block:
524
- puts DecNum.context.math{sin(1)*pi} # -> 2.643559064
525
- puts DecNum.math{sin(1)*pi} # -> 2.643559064
526
- # And can be *included* to be used as private instance methods:
527
- include DecNum::Math
528
- puts sin(1)*pi # -> 2.643559064
529
- end
530
-
531
- == More Information
532
-
533
- * Decimal Floating point type: see the base Flt::Num class and the Flt::DecNum class
534
- * Binary Floating point type: see the base Flt::Num class and the Flt::BinNum class
535
- * Floating Point Contexts: see documentation for classes Flt::Num::ContextBase,
536
- Flt::DecNum::Context and Flt::BinNum::Context
537
- * Floating Point Tolerance: see the flt/tolerance.rb[link:lib/flt/tolerance_rb.html] file
538
- and the Flt::Tolerance class
539
- * Constructors: see Flt.DecNum(), Flt.BinNum() and Flt.Tolerance().
540
- * Trigonometry functions: see Flt::Trigonometry.
541
- * Complex number support: see the flt/complex.rb[link:lib/flt/complex_rb.html] file
542
-
543
- = DecNum vs BigDecimal
544
-
545
- --
546
- EXPAND-
547
- ++
548
-
549
- DecNum solves some of the difficulties of using BigDecimal.
550
-
551
- One of the major problems with BigDecimal is that it's not easy to control the number of
552
- significant digits of the results. While addition, subtraction and multiplication are exact (unless a limit is used),
553
- divisions will need to be passed precision explicitly or else an indeterminate number of significant digits will be lost.
554
- Part of the problem is that numbers don't keep track of its precision (0.1000 is not distinguishable from 0.1.)
555
-
556
- With DecNum, Context objects are used to specify the exact number of digits to be used for all operations making
557
- the code cleaner and the results more easily predictable.
558
-
559
- DecNum.context.precision = 10
560
- puts DecNum(1)/DecNum(3)
561
-
562
- Contexts are thread-safe and can be used for individual operations:
563
-
564
- puts DecNum(1).divide(DecNum(e), DecNum::Context(:precision=>4))
565
-
566
- Which can be abbreviated:
567
-
568
- puts DecNum(1).divide(DecNum(e), :precision=>4)
569
-
570
- Or use locally in a block without affecting other code:
571
-
572
- DecNum.context {
573
- DecNum.context.precision = 3
574
- puts DecNum(1)/DecNum(3)
575
- }
576
- puts DecNum.context.precision
577
-
578
- Which can also be abbreviated:
579
-
580
- DecNum.context(:precision=>3) { puts DecNum(1)/DecNum(3) }
581
-
582
- This allows in general to write simpler code; e.g. this is an exponential function, adapted from the
583
- 'recipes' in Python's Decimal:
584
-
585
- def exp(x, c=nil)
586
- i, lasts, s, fact, num = 0, 0, 1, 1, 1
587
- DecNum.context(c) do |context|
588
- context.precision += 2
589
- while s != lasts
590
- lasts = s
591
- i += 1
592
- fact *= i
593
- num *= x
594
- s += num / fact
595
- end
596
- end
597
- return +s
598
- end
599
-
600
- The final unary + applied to the result forces it to be rounded to the current precision
601
- (because we have computed it with two extra digits)
602
- The result of this method does not have trailing non-significant digits, as is common with BigDecimal
603
- (e.g. in the exp implementation available in the standard Ruby library, in bigdecimal/math)
604
-
605
- --
606
- EXPAND+
607
- ++
608
-
609
- = Roadmap
610
-
611
- * Trigonometry optimizations
612
- * Implement the missing GDA functions:
613
- rotate, shift, trim, and, or, xor, invert,
614
- max, min, maxmag, minmag, comparetotal, comparetotmag