如何在Python中执行矢量化操作?

irlmq6kh  于 2023-02-28  发布在  Python
关注(0)|答案(3)|浏览(145)

我有一个问题,我的简单代码,这是假设是一个抵押贷款计算器,所有的利率从0.03到0.18都列在一个表中。

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

谢谢

wz3gfoph

wz3gfoph1#

问题是u是一个列表,它不能用于计算D时所做的矢量化操作。您可以将列表转换为NumPy数组以使代码工作。

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

或者,可以使用for循环或列表解析将u的每个元素的D存储为

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

但是在z = (a / D)期间,这将再次引起抱怨,因为D仍然是一个列表。因此,转换为数组似乎是一种方便的方法。
另一个备选答案是直接使用列表解析来计算z,而不涉及额外的变量D

z = [a / ((((i+1)**n)-1) /(i*(i+1)**n)) for i in u]
cnh2zyt3

cnh2zyt32#

你现在遇到的错误是因为u是一个列表(通过list comprehension生成),而D试图在u(一个列表)和数字之间执行数学运算,这是行不通的。
试试这个:

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

u是一个NumPy数组,可以用来做向量运算。如果你从来没有用过numpy模块,可以使用pip包管理器轻松安装。如果没有安装,那么

import numpy as np

将抛出一个错误,并且您将无法使用NumPy数组。如果您发现自己经常做类似的工作,则可能值得安装该程序。

omqzjyyz

omqzjyyz3#

如果你把初始列表r做成一个numpy数组,那么对它的每个操作都可以向量化。

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()

演示:https://trinket.io/python3/831425cc58

相关问题