Sotiris Zampelis
Sotiris Zampelis

Reputation: 55

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. 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. The algorithm should return a vector whose elements are in the form of StarterValueu^id^{N-i} i=0,\dots,N the simple algorithm i proposed is

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. 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?? thanks in advance. An example

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

Upvotes: 0

Views: 1321

Answers (1)

Roland
Roland

Reputation: 132999

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:

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

What happened? Apparently the multiplication became 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? Well, because of double overflow (read 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")).

You may need to use arbitrary precision numbers.

Upvotes: 3

Related Questions