计数算术运算 [英] Counting arithmetic operations
问题描述
有没有办法计算函数/表达式中数字运算(+、-、/、*)的次数?
Is there a way to evalute the number of numeric operations (+, -, /, *) in a function/expression?
以一个简单的线性代数问题为例(Ax = b
):
In example, lets take a simple linear algebra problem (Ax = b
):
A_data = np.array([[1, -4, 1],
[1, 6, -1],
[2, -1, 2]], dtype=float)
b_data = np.array([[7],
[13],
[5]], dtype=float)
接下来,让我们应用高斯消元过程:
Next, lets apply Gauss elimination procedure:
def gauss_elim(A, b):
Ab = np.column_stack((A, b))
for k, pivot_row in enumerate(Ab[:-1]):
for row in Ab[k+1:]:
if pivot_row[k] != 0:
row[k:] = row[k:] - pivot_row[k:] * row[k]/pivot_row[k]
return Ab
结果是:
array([[ 1. , -4. , 1. , 7. ],
[ 0. , 10. , -2. , 6. ],
[ 0. , 0. , 1.4, -13.2]])
我如何计算操作次数?
注意:我知道可以事先用数学方法评估运算次数(即对于 高斯消元法a> 是 O(n^3)).
Note: I know the number of operations can be evaluated mathematically beforehand (i.e. for Gaussian elimination it is O(n^3)).
推荐答案
如果你能花点时间,应该有一个方法:创建一个数字类并覆盖基本的算术方法:__add__
, __mul__
, __sub__
, __div__
通过在其中嵌入计数器系统(例如与某些全局变量相关).然后,您应该能够通过使用 dtype=object
参数(在创建数组时)来强制 Numpy 使用您的类型,以确保 Numpy 不会将您的数字转换为任何其他类型.我有时会为了更简单的任务而这样做;我从来没有用 Numpy 做过,但它应该可以工作.希望能帮到你.
If you can take a little time for it, there should be a way: create a class of numbers and override the basic arithmetic methods: __add__
, __mul__
, __sub__
, __div__
by embedding a counter system in it (related to some global variable for instance). You should then be able to force Numpy to use your type by using the dtype=object
parameter (at array creation) to make sure that Numpy doesn't convert your numbers to any other type. I sometimes did it for simpler task; I never did it with Numpy, but it should probably work. Hope it can help.
这篇关于计数算术运算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!