全部版块 我的主页
论坛 数据科学与人工智能 数据分析与数据科学 R语言论坛
4900 12
2014-10-16
如下所述:
cdf 的反函数分别是x=(2u)^1/2 u是小于1/2的, x=2-(2-2u)^1/2  u是大于等于1/2的
我的方法是先产生n个[0,1]均匀分布,再判断每一个u的大小,然后带到不同式子里,最后产生这个CDF的随机样本
程序如下
simfx=function(n)
{
output=0
x=0
t=0
u=runif(n)
for(i in 1:n)
while(t<n)
{
if(u[i]<(1/2))
{
x=(2*u)^(1/2)
t=t+1
output[t]=x
}
else((1/2)<=u[i])
{
x=2-(2-2*u)^(1/ 2)
t=t+1
output[t]=x
}
t
}
output
}


程序如上,不知道 为什么总是运行不了,求高人解答,实在太感谢了。

二维码

扫码加我 拉你入群

请注明:姓名-公司-职位

以便审核进群资格,未注明则拒绝

全部回复
2014-10-16 06:03:32
your code has a few problems,  try the following and see if it does what you need (i only fixed the code, you'll need to make sure the statistics is right, thanks)

simfx=function(n) {
  output=array(0,dim=n)
  u=runif(n)
  for(i in 1:n) {
     if(u[i]< 0.5) {
         x=(2*u[i])^(1/2)
         output[i]=x
     }
     else {
         x=2-(2-2*u[i])^(1/2)
         output[i]=x
     }
  }
  output
}


二维码

扫码加我 拉你入群

请注明:姓名-公司-职位

以便审核进群资格,未注明则拒绝

2014-10-16 06:06:49
fortr_cc 发表于 2014-10-16 06:03
your code has a few problems,  try the following and see if it does what you need (i only fixed the  ...
you don't need the x, can just do output=(2*u)^(1/2) for the 1st branch, and output=2-(2-2*u)^(1/2) for the 2nd.
二维码

扫码加我 拉你入群

请注明:姓名-公司-职位

以便审核进群资格,未注明则拒绝

2014-10-16 07:04:17
fortr_cc 发表于 2014-10-16 06:06
you don't need the x, can just do output=(2*u)^(1/2) for the 1st branch, and output=2-(2-2*u)^(1/2 ...
I fixed it as your suggestions, but it still was not working.
anyway, thanks
错误于output[t] = 2 - (2 - 2 * u)^(1/2) : 类别为'closure'的下标不对
此外: 警告信息:
1: In output = (2 * u)^(1/2) : 被替换的项目不是替换值长度的倍数
二维码

扫码加我 拉你入群

请注明:姓名-公司-职位

以便审核进群资格,未注明则拒绝

2014-10-16 09:11:59
试试这一句
复制代码
二维码

扫码加我 拉你入群

请注明:姓名-公司-职位

以便审核进群资格,未注明则拒绝

2014-10-16 13:10:30
whx229 发表于 2014-10-16 07:04
I fixed it as your suggestions, but it still was not working.
anyway, thanks
错误于output[t] = 2 ...
sorry i forgot the u, i thought you noticed the u in my longer code,  you only need to remove the x in the longer code.   (without u you'll get an error)

this is certainly the basic way of writing it out,  for someone versed in R, he could likely write it in just one line of code
二维码

扫码加我 拉你入群

请注明:姓名-公司-职位

以便审核进群资格,未注明则拒绝

点击查看更多内容…
相关推荐
栏目导航
热门文章
推荐文章

分享

扫码加好友,拉您进群