-1

Under Matlab 2014b, when making:

round((0.1:0.2:1)/0.2)

I obtain:

1 2 3 3 5

Instead of

1 2 3 4 5

Is there a way to fix such weird computation? Why this happens? Why so weird? This repeats for other values, not only n=0.2.

EDIT: I checked the duplicate but, do the scenario changes when using ceil so the floating point threshold is not in the half integer (0.5, 1.5, 2.5) but in the integer (1.0, 2.0, 3.0)? What if i use some other representation, like single? Or any other more predictable?

Brethlosze
  • 1,533
  • 1
  • 22
  • 41
  • 3
    `round((0.1:0.2+eps:1)./0.2)` – bla Dec 06 '17 at 00:04
  • 1
    get use to floating point accuracy... – bla Dec 06 '17 at 03:54
  • You can just use [`ceil`](https://www.mathworks.com/help/matlab/ref/ceil.html) instead of `round`. – gnovice Dec 06 '17 at 05:03
  • I suppose... `ceil` is equally prone to fail that `round` under the same scenario? – Brethlosze Dec 06 '17 at 13:22
  • 1
    Any operation where you are converting from floating point to integer values will potentially suffer this kind of error. This is because they are threshold based. `round` has a threshold at 0.5, so if your floating-point numbers all hover around that value, with slight errors above and below, you're going to see problems like what you have in your question. Likewise, `ceil` or `floor` will show the same problems if your floating-point numbers are close to integer values. The key is to pick thresholds that are farthest from your areas of numeric uncertainty. – gnovice Dec 06 '17 at 15:50

1 Answers1

1

since the question got reopened, I'll briefly mention that adding 1.3+0.2 with floats can result in 2.49999999999 or in 2.5000000001 etc. the round will act according to the floating point error.

bla
  • 25,846
  • 10
  • 70
  • 101