简体   繁体   English

R直方图中断错误

[英]R histogram breaks Error

I have to prepare an algorithm for my thesis to cross check a theoretical result which is that the binomial model for N periods converges to lognormal distribution for N\\to \\infty. 我必须为我的论文准备一种算法以交叉检验理论结果,即N个周期的二项式模型收敛到N \\ to \\ infty的对数正态分布。 For those of you not familiar with the concept i have to create an algorithm that takes a starter value and multiplies it with an up-multiplier and a down multiplier and continues to do so for every value for N steps. 对于那些不熟悉该概念的人,我必须创建一个算法,该算法采用一个起始值并将其乘以一个上乘数和一个下乘数,并针对N步的每个值继续这样做。 The algorithm should return a vector whose elements are in the form of StarterValue u^i d^{Ni} i=0,\\dots,N the simple algorithm i proposed is 该算法应返回一个向量,该向量的元素形式为StarterValue u ^ i d ^ {Ni} i = 0,\\ dots,N我提出的简单算法是

rata<-function(N,r,u,d,S){

  length(x)<-N
  for(i in 0:N){
    x[i]<-S*u^{i}*d^{N-i}
  }
  return(x)
}

N is the number of periods and the rest are just nonimportant values (u is for the up d for down etc) In order to extract my results i need to make a histogram of the produced vector's logarithm to prove that they are normally distributed. N是周期数,其余的只是不重要的值(u是向下的向上d,等等)为了提取我的结果,我需要对所产生矢量的对数进行直方图证明它们是正态分布的。 However for a N=100000( i need an great number of steps to prove convergence) when i type hist(x) i get the error :(invalid number of breaks) Can anyone help?? 但是对于N = 100000(我需要大量步骤来证明收敛),当我键入hist(x)我会得到error :(invalid number of breaks)有人可以帮忙吗? thanks in advance. 提前致谢。 An example 一个例子

 taf<-rata(100000,1,1.1,0.9,1)
 taf1<-log(taf)
 hist(taf1,xlim=c(-400,400))

First I fix your function: 首先,我修复您的功能:

rata<-function(N,r,u,d,S){
  x <- numeric(N+1)
  for(i in 0:N){
    x[i]<-S*u^{i}*d^{N-i}
  }
  return(x)
}

Or relying on vectorization: 或依靠矢量化:

rata<-function(N,r,u,d,S){
  x<-S*u^{0:N}*d^{N-(0:N)}
  return(x)
}

taf<-rata(100000,1,1.1,0.9,1) 

Looking at the result, we notice that it contains NaN values: 查看结果,我们注意到它包含NaN值:

taf[7440 + 7:8]
#[1]   0 NaN 

What happened? 发生了什么? Apparently the multiplication became NaN : 显然,乘法变为NaN

1.1^7448*0.9^(1e5-7448)
#[1] NaN

1.1^7448
#[1] Inf

0.9^(1e5-7448)
#[1] 0

Inf * 0
#[1] NaN

Why does an Inf value occur? 为什么会出现Inf值? Well, because of double overflow (read help("double") ): 好吧,由于两次溢出(请阅读help("double") ):

1.1^(7440 + 7:8)
#[1] 1.783719e+308           Inf

You have a similar problem with floating point precision when a multiplicant gets close to 0 (read help(".Machine") ). 当乘数接近0时,浮点精度也会遇到类似的问题(请阅读help(".Machine") )。

You may need to use arbitrary precision numbers. 您可能需要使用任意精度数字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM