1
Probability = 0.52;
SharePrice = 215;
n = 10000;
count = 0;
count250 = 0;
count200 = 0;

for i = 1:n
    CoinToss = rand(1);
    if (SharePrice == 200)
        break;
    end
     if (SharePrice == 250)     
        break;
    end
    if(Probability < CoinToss)
        SharePrice = SharePrice - 0.2;        
    else
        SharePrice = SharePrice + 0.2;        
    end  
end

The code just seems to go on beyond the bound I've given (200 and 250), why doesn't it stop?

James
  • 41
  • 7
  • I feel like this should have a simple answer. – James Nov 07 '17 at 22:16
  • 2
    Welcome to floating point arithmetic. As an experiment, try `(215-0.2) == (214.6+0.2)`. You'll see that they're not equal. If you print out `215-0.2` to more decimal places, you'll see `fprintf('%.17g\n', 215-0.2)` gives `214.80000000000001`. – beaker Nov 07 '17 at 22:17

1 Answers1

0

Welcome to floating-point inaccuracies; your SharePrice likely doesn't add up to exactly 200, so it'll end up failing the SharePrice == 200 condition (and the same goes for SharePrice == 250).

You should consider breaking out of your loop if SharePrice is below 200 or above 250:

if (SharePrice <= 200)
    break
end
if (SharePrice >= 250)     
    break
end
frslm
  • 2,969
  • 3
  • 13
  • 26
  • 1
    This will lead to inaccuracies. If you decrement `215` by `0.2` each time, it will take 76 iterations before `SharePrice <= 200` instead of the correct 75 iterations. – beaker Nov 07 '17 at 22:20
  • So what is the correct way to address the issue? – James Nov 07 '17 at 22:22
  • @James Read the linked dupe target – Sardar Usama Nov 07 '17 at 22:24
  • 1
    If @James isn't concerned about tracking the exact number of iterations their (almost) random walk takes to reach a bound, then this approach should be fine. Otherwise, for this particular scenario, they could change the `SharePrice` step to some integral value (e.g. 2 instead of 0.2, and scale the other values by 10x) to avoid working with floating-point numbers. – frslm Nov 07 '17 at 22:24