I wanted to implement the cantor function in R and plot it. I only know Python and Java so R is new for me. The cantor function is defined as:
Let f0(x) = x.
Then, for every integer n ≥ 0, the next function fn+1(x) will be defined in terms of fn(x) as follows:
Let fn+1(x) = 1/2 × fn(3x), when 0 ≤ x ≤ 1/3 ;
Let fn+1(x) = 1/2, when 1/3 ≤ x ≤ 2/3 ;
Let fn+1(x) = 1/2 + 1/2 × fn(3 x − 2), when 2/3 ≤ x ≤ 1.
This is my code:
cantor <- function(x,n){
if (n==0){
return(x)
}else{
if(0 <= x & x <= 1/3){
return(1/2*cantor(3*x,n-1))
}else if(1/3 < x & x < 2/3){
return(1/2)
}else{
return(1/2+1/2*cantor(3*x-2,n-1))
}
}
}
which works well as long as it has an single input. But if I try to plot it over x=seq(0,1,0.01) it does not work because my conditions are for single inputs but R gives the whole vector x to my function.
Is there a way to have only an single input over an vector or how do I rewrite my code so it works.
Aucun commentaire:
Enregistrer un commentaire