mardi 21 avril 2020

Random numbers in a class not persisting

I'm currently learning python and have been testing myself with writing a class, with defs inside. As you can see from running the class below with a specific set of input parameters, two print statements for the currency increase yields different values - due to the use of random when calculating the interest on a month by month basis.

Maybe my approach of doing this within a class is wrong, but is there a way to 'freeze' the results of my 'test' variable? For example, when I want to print my profit, it is printing the profit of a new execution of the class, using different random numbers. Imagine if I want to add a plot function at a later date to track this in another def in the class, it is again going to plot a different graph!

If this is not the correct approach to deal with this sort of problem, I'd love to be pointed in the right direction.

import random


class currency:
    def __init__(self, months, monthly_invest, percent):
        self._months = months
        self._monthly_invest = monthly_invest
        self._percent = percent
        self._random = random.uniform(-percent, percent)

    def currencyIncrease(self):
        currencyValue = 150
        currencyInterest = 0.01 * self._random
        quantity_bought = 0
        for i in range(self._months):
            quantity_bought = quantity_bought + self._monthly_invest / currencyValue
            currencyValue = currencyValue * (1 + currencyInterest)
            currencyInterest = 0.01 * random.uniform(-self._percent, self._percent)
        total_return = currencyValue * quantity_bought
        return currencyValue, quantity_bought, total_return

    def saving(self):
        total_invest = 0
        for i in range(self._months):
            total_invest = total_invest + self._monthly_invest
        return total_invest


test = currency(12, 200, 15)
profit = test.cryptoIncrease()[2] - test.saving()
print(test.currencyIncrease())
print(test.currencyIncrease())
print(profit)
print(profit)



Aucun commentaire:

Enregistrer un commentaire