Ruby BigDecimal sanity check (floating point newb) -


Am I sure that with Ruby BigDecimal types (different exact and scale length Also) should accurate calculations or expect me of the temporary point shenanigans?

All of my values ​​are in the form of a BigDecimal within a Rail app and I see some errors (they have different decimal lengths), hopefully this is just my way and Not of my object type.

There are two general disadvantages arithmetic while working with floating point.

The first problem is that the Ruby Floating Points are fixed accurately. In practice it will either be 1) There is no problem for you or 2) Destructive, or 3) Something in between Consider the following:

  # float 1.0 e + 25 - 99 99999999999999900000000.0 # = & gt; 0.0 # BigDekelom BigDecal ("1.0E + 25") - BigDecimal ("9999999999999999900000000.0") # = & gt; 100000000  

100 million accurate difference! Very serious, right?

Exact error, except 0.0000000000001% of the original number, it really depends on you whether it is a problem or not. But the problem has been removed using BigDecimal because its uncontrolled precision is your only limit available memory for Ruby.

The second problem is that Floating Points can not express all the parts correctly, they have problems with decimals fractions, Because floats (and most other languages) in Ruby are floating point binary for example, decimal fraction 0.2 is a seamless-repeated binary fraction ( 0.001100110011 ... < / Code>). This can not be correctly stored in the binary floating point, even if it is precision.

When you are doing a rounding number, it will have a big impact. Consider:

# Float (0.2 9 * 50). # # = & Gt; 14 # True # BigDecamel (BigDecale ("0.2 9") * 50). The description of decimals may be exact, # # and = 15 # correct

A BigDecimal . However, there are some excerpts that can not be correctly described with decimals, for example 1/9 a continuous-repeating decimal decimals ( 0.1111111111111 ... ) is.

Again, when you score a number, it will bite you. Consider:

  # BigDecamel (BigDecale ("1") / 9 * 9/2). ## and = 0 # is not true  

In this situation, using decimal floating points will still use a round error.

Some findings:

  • If decides with decimal decimals (money, for example), decimal floats are horrible.
  • Ruby's BigDecimal also works well if you do not care about temporary precision floating points, and indeed if they are decimal or binary floating points.
  • If you work with (scientific) data, then you are usually working with fixed precision numbers; The underlying floats of Ruby are probably enough.
  • You can not expect any type floating point to be accurate in all situations.

Comments

Popular posts from this blog

windows - Heroku throws SQLITE3 Read only exception -

lex - Building a lexical Analyzer in Java -

python - rename keys in a dictionary -