计数算术运算

编程入门 行业动态 更新时间:2024-10-10 03:32:08
本文介绍了计数算术运算的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

有没有办法计算函数/表达式中数字运算(+、-、/、*)的次数?

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.

更多推荐

计数算术运算

本文发布于:2023-11-30 15:42:57,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1650550.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:算术

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!