Linspace与范围 [英] Linspace vs range
问题描述
我想知道哪种样式更好/更有效:
I was wondering what is better style / more efficient:
x = linspace(-1, 1, 100);
或
x = -1:0.01:1;
推荐答案
正如奥利·查尔斯沃思(Oli Charlesworth)所提到的,在linspace
中,将区间[a,b]
划分为N
个点,而对于:
形式,您可以-以指定的步长(默认值为1)从a
跳出,直到达到b
.
As Oli Charlesworth mentioned, in linspace
you divide the interval [a,b]
into N
points, whereas with the :
form, you step-out from a
with a specified step size (default 1) till you reach b
.
要记住的一件事是,linspace
总是包含端点,而:
形式将包含第二个端点,只有当步长足够大时在最后一步落在它上面,它将落空.示例:
One thing to keep in mind is that linspace
always includes the end points, whereas, :
form will include the second end-point, only if your step size is such that it falls on it at the last step else, it will fall short. Example:
0:3:10
ans =
0 3 6 9
也就是说,当我使用两种方法时,取决于我需要做的事情.如果我需要做的只是采样固定点数的间隔(并且我不在乎步长),则使用linspace
.
That said, when I use the two approaches depends on what I need to do. If all I need to do is sample an interval with a fixed number of points (and I don't care about the step-size), I use linspace
.
在很多情况下,我不在乎它是否不落在最后一点上,例如,当使用极坐标时,我不需要最后一点,因为2*pi
与0
.在那里,我使用0:0.01:2*pi
.
In many cases, I don't care if it doesn't fall on the last point, e.g., when working with polar co-ordinates, I don't need the last point, as 2*pi
is the same as 0
. There, I use 0:0.01:2*pi
.
这篇关于Linspace与范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!