Home > Software engineering >  Getting incorrect result when using floor() while calculating compount interest
Getting incorrect result when using floor() while calculating compount interest

Time:08-04

In my code, I use the well-known formula for calculating compound interest. I used floor() for every element in the result, but I got an unexpected result, i.e. for 6 months I got [1300, 1690, 2197, 2856, 3712, 4826] where the last number should be 4825, if calculating manually every time skipping decimals (what floor() actually should do in my loop but it doesn't for the last number).

The question is why? How overcome this "error"?

Here is my code:

from math import floor

def get_plan(current_production: int, month: int, percent: int):

    monthly_production = []
    for i in range(1, month   1):
        #calculating percentage using compound interest formula
        monthly_production.append(floor(current_production * (1   percent / 100) ** i))
    return monthly_production 

get_plan(1000, 6, 30)

CodePudding user response:

Substituting the given values you get 1000 * (1 30 / 100) ** 6 which is 4826.809000000001 in floats and correctly floored to 4826. I suppose the issue is that your intermediate results aren't floored: When you calculate it manually, you say you "throw away the decimals from every result" (after every step).

To fix this in your Python code, simply don't use float exponentiation which doesn't floor after every multiplication but instead multiply with the interest in each step:

from math import floor

def get_plan(current_production: int, month: int, percent: int):
    monthly_production = []
    for i in range(1, month   1):
        #calculating percentage using compound interest formula
        current_production = floor(current_production * (1   percent / 100))
        monthly_production.append(current_production)
    return monthly_production 

get_plan(1000, 6, 30) correctly yields [1300, 1690, 2197, 2856, 3712, 4825] then.

  • Related