0

First I seperate integer part and floating part of a floating value with 4 digits (e.g. 5.678) Next I multiply the floating part by 1000 to get an integer and then put this integer into floor function.

x = 5.678
int_part = floor (x)            % result is 5
float_part = x - int_part       % result is 0.678
float_part = float_part * 1000  % result is 678
floor (float_part)              % returns 677 instead of 678

What's going on here? How can I tell Matlab/Octave to return the right value?

Thx in advance

flappix
  • 2,038
  • 17
  • 28
  • 8
    The reason is that `5.678-5==0.678` returns `0`, ie. `false` due to machine-precision arithmetic. Try adding `eps` to your remainder: `float_part=x-int_part+eps`. Some info: http://stackoverflow.com/questions/686439/why-is-24-0000-not-equal-to-24-0000-in-matlab – Andras Deak -- Слава Україні Nov 16 '15 at 23:44
  • Display more digits using `format long g` to see how `5.678` is being stored. – Matt Nov 16 '15 at 23:46

1 Answers1

1
x = 5.678
int_part = floor (x)            % result is 5
float_part = x - int_part       % result is 0.678
float_part = float_part * 1000  % result is 678
floor (float_part)              % returns 677 instead of 678
format long
disp(float_part)

The answer is

6.779999999999999e+02

So the floor(float_part) is

677
Shuaib Ahmed
  • 134
  • 3