1
I was doing Python exercises and came across the following problem.
Assuming that the population of a country A is on the order of 80000 inhabitants with an annual growth rate of 3% and that the population of B is 200000 inhabitants with a growth rate of 1.5%. Make a program that calculates and writes the number of years necessary for the population of the country A to exceed or equal the population of the country B, maintained growth rates. So I tried to solve it this way:
A = population 1 = 80000
B = population 2 = 200000
time = 0
while A != B:
A = A + A*(0.03)
B = B + B*(0.015)
tempo = tempo + 1
else:
print(A,B,tempo)
Conduit, when I run the program, appears 'inf inf'' for A and B and the time gives a very large number. I found a solution on the internet, but I do not understand why there is difference. The solution only modifies the operator !=
by the operator <
:
while A < B:
A = A + A*(0.03)
B = B + B*(0.015)
tempo = tempo + 1
else:
print(A,B,tempo)
I understand that if A is smaller than B the solution also works. But why if A is different from B the solution doesn’t work?
Why perhaps the variables being compared never reach an exactly equal value, even because the floating point data type is inherently inaccurate and should not be used in strict equality tests.
– anonimo