TDD Basics : Testing computation involving floating-point numbers
- Floating-point numbers are not real.
They are approximation of real numbers, there is inevitably a little error present. This error, called roundoff, can lead to surprising results. You should not use floating-point numbers for financial applications. They are intended for efficient scientific computation.
Tip by Chuck Allison from the book 97 Things a Programmer Should Know
We can compare adding two floats as follows:
> (0.25 + 0.79) => 1.04 > (0.25 + 0.79) == 1.04 => true
You see that the result of adding these two numbers is a Float:
(139.25 + 74.79).class => Float
Let's now consider this example:
> 139.25 + 74.79 => 214.04000000000002 > (139.25 + 74.79) => 214.04000000000002 > (139.25 + 74.79) == 214.04 => false
Floats cannot store decimal numbers precisely. If we are interested only in comparing upto two decimal places, we can do so in our test like this:
describe 'Float accuracy' do it 'should be within a given decimal places' do x = 139.25 y = 74.79 expect(x + y).to be_within(0.001).of(214.04) end end
Run the spec:
It will pass.
Ace the Technical Interview
- Easily find the gaps in your knowledge
- Get customized lessons based on where you are
- Take consistent action everyday
- Builtin accountability to keep you on track
- You will solve bigger problems over time
- Get the job of your dreams
Take the 30 Day Coding Skills Challenge
Gain confidence to attend the interview