Number Flashcards Preview

Ruby > Number > Flashcards

Flashcards in Number Deck (3)
Loading flashcards...
1
Q

How to transform numbers into binary code?

A

10.to_s(2) # => “1010”

2
Q

Can you provide an example of when float numbers are inaccurate and return the wrong values?

A
# first 
a = 0.0
1000.times { a += 1.1 }
# a == 1100.0000000000086 

second

1.4 + 1.2 
# 2.5999999999999996
3
Q

How to fix the problem using inaccurate float value?

A
1.4 + 1.2 
# 2.5999999999999996
# solution 1 use rational numbers
(1.4r + 1.2r).to_f
# 2.6

solution 2 use BigDecimal
require ‘bigdecimal’
BigDecimal(‘1.2’) + BigDecimal(‘1.4’)