How to perform vectorized operations in Python?

Question:

I’m having an issue with my simple code that is suppose to be a mortgage calculator where all the rates from 0.03 to 0.18 are listed in a table. Here is my code and error.

l = 350000 #Loan amount
n = 30 #number of years for the loan
r = [0.03,0.04,0.05,0.06,0.07,0.08,0.09,0.10,0.11,0.12,0.13,0.14,0.15,0.16,0.17,0.18] #interest rate in decimal

n = n * 12
a = l
int1 = 12
u = [x / int1 for x in r]

D = (((u+1)**n)-1) /(u*(u+1)**n)

z = (a / D)
print(z)

File "test.py", line 23, in <module>
    D = (((u+1)**n)-1) /(u*(u+1)**n)
TypeError: can only concatenate list (not "int") to list

Thanks

Asked By: Colin L

||

Answers:

The problem is that u is a list which cannot be used for vectorized operation which you are doing while computing D. You can convert your list to a NumPy array to make your code work.

u = np.array([x / int1 for x in r])

Alternatively, you can use a for loop or list comprehension to store D for each element of u as

D = [(((i+1)**n)-1) /(i*(i+1)**n) for i in u]

but this will again complain during z = (a / D) because D is still a list. Therefore, converting to array seems to be a convenient approach.

The another alternative answer is to compute z using list comprehension directly without involving extra variable D

z = [a / ((((i+1)**n)-1) /(i*(i+1)**n)) for i in u]
Answered By: Sheldore

The current error you’re facing is because u is a list (made via a list comprehension), and D tries to perform math operations between u (a list) and numbers. That won’t work.

Try this:

import numpy as np
u = np.array([x / int1 for x in r])

u will be a NumPy array, which allows you to do vector math with it. If you’ve never used the numpy module, it’s an easy install using the pip package manager. If it’s not installed then

import numpy as np

will throw an error, and you will not be able to use a NumPy array. If you find yourself doing similar work often, it’s likely worth the installation.

Answered By: charley

If you make the initial list r a numpy array, every operation on it can be vectorised.

import numpy as np
from pprint import pprint


l = 350000 #Loan amount
n = 30 #number of years for the loan
r = np.array([0.03,0.04,0.05,0.06,0.07,0.08,0.09,0.10,0.11,0.12,0.13,0.14,0.15,0.16,0.17,0.18]) #interest rate in decimal

n = n * 12
a = l
int1 = 12

u = r / int1  #vectorised
pprint(list(u))
print()
print()


D = (((u+1)**n)-1) /(u*(u+1)**n)  #vectorised

z = (a / D)  #vectorised
pprint(list(z))
print()
print()


# list comprehension alternative, to compare results.
z = [a / ((((i+1)**n)-1) /(i*(i+1)**n)) for i in u]
pprint(list(z))
print()
print()

Demo: https://trinket.io/python3/831425cc58

Answered By: MatBailie
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.