Inf在Matlab中的应用

2024-06-26 00:12:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前正在将一个MATLAB程序翻译成Python。我使用numpy成功地移植了之前所有的向量操作。然而,我被困在下面的代码,这是一个余弦相似性度量。在

% W and ind are different sized matrices
dist = full(W * (W(ind2(range),:)' - W(ind1(range),:)' +  W(ind3(range),:)')); 
for i=1:length(range)
    dist(ind1(range(i)),i) = -Inf;
    dist(ind2(range(i)),i) = -Inf;
    dist(ind3(range(i)),i) = -Inf;
end
disp(dist)
[~, mx(range)] = max(dist);

我不明白下面的部分。在

^{pr2}$

当你使用

= -Inf;

在右边?在


Tags: and代码程序numpy度量distrange相似性
3条回答

Inf通常用于初始化一个变量,以便以后可以在循环中使用它进行比较。 例如,如果我想找到函数中的最大值(但忘记了max命令)。然后我会做一些类似的东西:

function maxF = findMax(f,a,b)
maxF = -Inf;
x = a:0.001:b;
for i = 1:length(x)
    if f(x) > maxF
         maxF = f(x);
    end
end

这是matlab中的一种方法,确保任何其他值都大于电流。所以在Python中的比较应该是-系统最大值+1。在

例如,请参见: Maximum and Minimum values for ints

它只是在左边指定一个minus infinity值。在

分配这个值可能看起来很奇怪,特别是因为距离cannot be negative。但是它看起来像是用来有效地从最后一行的max计算中删除那些条目。在

如果Python没有“infinity”(我不知道Python)如果dist真的是一个距离(因此非负),您可以使用任何负值而不是-inf来达到相同的效果,即从max计算中删除这些条目。在

在Matlab中(参见:Inf):

Inf returns the IEEE® arithmetic representation for positive infinity.

因此Inf产生一个大于所有其他数值的值。-Inf生成一个保证小于任何其他数值的值。当你想迭代地找到一个最大值,并且需要一个比第一个值小的第一个值时,通常使用它。在

根据维基百科(见:IEEE 754 Inf):

Positive and negative infinity are represented thus:

sign = 0 for positive infinity, 1 for negative infinity.
biased exponent = all 1 bits.
fraction = all 0 bits.

Python使用'-inf'具有相同的概念(请参见注释6here):

float also accepts the strings “nan” and “inf” with an optional prefix “+” or “-” for Not a Number (NaN) and positive or negative infinity.

>>> a=float('-inf')
>>> a
-inf
>>> b=-27983.444
>>> min(a,b)
-inf

相关问题 更多 >