Skip to content Skip to sidebar Skip to footer

Pset2 Python Problem3-UsingBisectionSearch.py

I am completely new to Python, and I have lots of problems working out indentation, anyway I need someone to help me understand why my code not working...( The if condition is not

Solution 1:

You should be deducting ans not monthlyPayment, setting monthlyPayment = ans outside the loop does not mean monthlyPayment will be updated when you set ans = (Low + High) / 2.0 inside the while loop each time, you are creating a new object each time:

while abs(newbalance) > 0.001: # check if we are withing +- .001 of clearing balance
    newbalance = balance
    month = 0
    for month in range(12): # loop over 12 month range
        print('low = ' + str(Low) + ' high = ' + str(High) + ' ans = ' + str(ans))
        newbalance -= ans # deduct ans not the the original value set outside the while
        interest = monthlyInterestRate * newbalance
        newbalance += interest
        print month    
    if newbalance > 0:
        Low = ans
    else:
        High = ans    
    ans = (Low + High) / 2.0    
print "Lowest Payment: {:.2f}".format(ans) # format to two decimal places

Also it is better to use for month in range(12), we know we only want to have 12 iterations so much simpler to use range.

Even if you were doing a ans += 2 your monthlyPayment would not be updated as ints are immutable so monthlyPayment would still only point to the original value of ans.

In [1]: ans = 10    
In [2]: monthlyPayment = ans    
In [3]: id(ans) 
Out[3]: 9912448    
In [4]: id(monthlyPayment) # still the same objects
Out[4]: 9912448    
In [5]: ans += 10 # creates new object
In [6]: ans
Out[6]: 20    
In [7]: monthlyPayment # still has original value
Out[7]: 10  
In [8]: id(monthlyPayment)  # same id as original ans
Out[8]: 9912448     
In [9]: id(ans)  # new id because it is a new object
Out[9]: 9912208

Post a Comment for "Pset2 Python Problem3-UsingBisectionSearch.py"