Growth rate using PHP

Asked

Viewed 59 times

2

I’m having trouble making a simple monthly growth calculation using PHP. There is the problem that it is not possible to divide by zero.

The formula used is as follows::

$taxaDeCrescimento = ((($quantidadeMesATUAL - $quantidadeMesPassado) / $quantidadeMesPassado) * 100);

I’m basing this calculation on this formula of growing up. inserir a descrição da imagem aqui

But I would like this calculation to work in months past where it obtained the value of quantity equal to zero. That is, if last month got quantity 0 and this month had quantity 2. Get a growth percentage of 200%. What would be the solution to this problem?

  • 1

    What you’re calculating is relative growth and there’s no way to calculate that from zero. Having a 200% growth rate means that you have doubled the previous value. If it was 100, it was 200; if it was 500, it was 1000. The growth rate from 0 to 2 (or any value) tends to infinity.

  • It’s a college exercise ???

  • 1

    No @Virgilionovic, it’s a problem I’m solving in a system

  • @Andersoncarloswoss this form in the practice of the system I’m doing would work perfectly. Because the "quantityMesAtual" never reaches zero. But when it comes to performing my tests if they are functional, I realize that every month with such a "quantity" there are several that reach zero. Because there was nothing inserted in the perido so that this amount is not zero.

  • I am mainly in doubt of what I can do about it.

  • But if the zero quantity situation should not happen in production, then I see no reason to consider it in the account. You just make a if checking if it is zero and returning an error.

Show 1 more comment

1 answer

1


Good afternoon, you could try testing for when it is zero, split by 1, so the split would not give error and return the original value:

$taxaDeCrescimento = ((($quantidadeMesATUAL - $quantidadeMesPassado) / (($quantidadeMesPassado) ? $quantidadeMesPassado : 1)) * 100);

But this would only work if you changed the division parameter, keeping the subtraction parameter intact.

Using your example: ((2 - 0) / 1) *100 -> 2-0=2 -> 2/1=2 -> 2*100= 200%

I hope I’ve been clear and able to help you.

  • You could simplify using the operator Elves: $quantidadeMesPassado ?: 1, but anyway making the division by 1 will return a wrong value (mathematically speaking). If I go from 0 to 2 or go from 1 to 2 I would have the same growth rate. It makes no sense.

  • This depends, because if the current value is 5 and the previous 0, 5-0=5 and the division would be by 1, being any number divided by 1 equal to itself, the value of the equation would be 5, and the multiplication after that.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.