在matlab中生成随机负到正浮点数

generate random negative to positive float numbers in matlab

如何生成介于 -0.01 和 0.01 之间的随机值?那行不通:

rand()-(0.01);

我在互联网上找到的许多其他方法都不起作用。看起来很容易,但我快要疯了。

来自documentation

In general, you can generate N random numbers in the interval (a,b) with the formula:

r = a + (b-a).*rand(N,1)

在您的特殊情况下,如果您希望在区间 (-0.01, 0.01) 内生成 10 个随机数,您可以这样做:

r = -0.01 + (0.01-(-0.01)).*rand(10,1)

给出:

r =

    0.0081
   -0.0075
    0.0083
    0.0026
   -0.0080
   -0.0044
    0.0009
    0.0092
    0.0093
   -0.0068

(2*rand() - 1) / 100.0 应该可以胜任。这是@Cebri 更一般性回答的特例。

  • rand(): [0, 1]
  • 2*rand(): [0, 2]
  • 2*rand()-1: [-1, 1]
  • (2*rand()-1)/100: [-0.01, 0.01]