R:为什么这不起作用?矩阵、舍入误差?

发布于 2024-09-26 08:31:40 字数 402 浏览 1 评论 0原文

为什么这有效:

ncota <- 1
nslope <- 29
resul <- matrix(rep(0,ncota*nslope*4),ncota*nslope,4)

但这不起作用?

ncota <- 1
sini <- 0.1; sfin <- 1.5; spaso <- 0.05; nslope <- 1+((sfin-sini)/spaso)
resul <- matrix(rep(0,ncota*nslope*4),ncota*nslope,4)

我猜问题是除法给出了一个非整数。 我怎样才能让第二个工作? 我需要创建一个零矩阵,其大小是通过方程计算计算出来的。

干杯

Why this works:

ncota <- 1
nslope <- 29
resul <- matrix(rep(0,ncota*nslope*4),ncota*nslope,4)

But this doesn't?

ncota <- 1
sini <- 0.1; sfin <- 1.5; spaso <- 0.05; nslope <- 1+((sfin-sini)/spaso)
resul <- matrix(rep(0,ncota*nslope*4),ncota*nslope,4)

I guess the problem is that the division gives a noninteger number.
How can I get the second one work?
I need to create a zero matrix with its size calculated from a equation calculation.

cheers

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

反差帅 2024-10-03 08:31:40

如果您所要做的就是创建一个零矩阵,则不需要提供正确数量的零,只需提供一个并让 R 将其回收到所需的长度:

matrix(0, ncota*nslope, 4)

第二个失败的原因是 ncota * nslope * 4 不完全是 116:

> (ncota * nslope * 4) == 116
[1] FALSE
> all.equal(ncota * nslope * 4, 116)
[1] TRUE

all.equal 显示,如果您允许浮点误差,则这些是相等的。

?rep 包括以下内容:

 Non-integer values of ‘times’ will be truncated towards zero.  If
 ‘times’ is a computed quantity it is prudent to add a small fuzz.

如果我们按照它所说的去做并添加一个小绒毛,rep 确实会给出所需的 0 数量:

> length(rep(0, times = ncota*nslope*4 + 0.00000001))
[1] 116

正如 Hadley 所指出的(在评论中) ),可以使用 zapsmall 函数轻松添加此模糊:

> length(rep(0, times = zapsmall(ncota*nslope*4)))
[1] 116

If all you have to do is create a matrix of zeroes, you don't need to supply the correct number of zeroes, just supply one and let R recycle it to the required length:

matrix(0, ncota*nslope, 4)

The reason the second one fails is that ncota * nslope * 4 is not exactly 116:

> (ncota * nslope * 4) == 116
[1] FALSE
> all.equal(ncota * nslope * 4, 116)
[1] TRUE

all.equal shows that these are equal if you allow for the floating point error.

?rep includes the following:

 Non-integer values of ‘times’ will be truncated towards zero.  If
 ‘times’ is a computed quantity it is prudent to add a small fuzz.

and if we do as it says and add a small fuzz, rep does give the desired number of 0s:

> length(rep(0, times = ncota*nslope*4 + 0.00000001))
[1] 116

As noted by Hadley (in the comments), this fuzz can be easily added using the zapsmall function:

> length(rep(0, times = zapsmall(ncota*nslope*4)))
[1] 116
情绪少女 2024-10-03 08:31:40

您不需要使用rep。这工作得很好:

resul <- matrix(0,ncota*nslope,4)

You don't need to use rep. This works just fine:

resul <- matrix(0,ncota*nslope,4)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文