1

It is formula that I use to find distance traveled by bouncing ball:
enter image description here
where:
h(n) - total distance traveled by bouncing ball
H - a ball drop height
n - number of bounces
e - coefficient of restitution

I created Matlab function to do that calculation:

function distance = totalDistance(H, n, e)
sum = 0;
bounceHeight = 0;
    for i = 1:n
        bounceHeight  = H*(e^(2*n));
        sum = sum + e^(2*n);
    end
distance = H+(2*H*sum);
end

This function takes initial drop height H, number of bounces n, coefficient of restitution e and returns me total distance traveled by bouncing ball.

Then I call this function in command window to check:

totalDistance(2,2,2)

The function returns wrong result. It returns 130 instead of 82.

Why the program does not work properly?

Erba Aitbayev
  • 4,167
  • 12
  • 46
  • 81
  • Do not be confused by bounceHeight variable. It does not matter at the moment. I was planning to use it later. – Erba Aitbayev Sep 19 '15 at 20:29
  • 2
    Do not use `i` as a [variable](http://stackoverflow.com/questions/14790740/using-i-and-j-as-variables-in-matlab) and don't overwrite the build-in function `sum`. That's bad programming and prone for errors – Adriaan Sep 19 '15 at 20:40

1 Answers1

2

Firstly, everything @Adriaan said in the comment applies.

You have a couple issues in addition to that: 1. The variable bounceHeight is unused. 2. You need to add e^(2*i) instead of e^(2*n).

What you are trying to do can also be accomplished in simpler (and more efficient code):

h = H + 2*H*sum(e.^(2:2:2*n));

what the sum in particular does is sum over all elements of an array created by the variable e which is raised to the power of a list, beginning at 2, ending at 2n, in increments of 2.

Hope this helps.

pragmatist1
  • 919
  • 6
  • 16
  • ah, I think the "coefficient of restitution" is actually also an overwritten build-in in this case. I expected it to be just the regular exponential function judging from the OP's formula – Adriaan Sep 19 '15 at 21:08