abhijato
abhijato

Reputation: 15

Complex number containing vectors in R

I am trying to make a Mandelbrot set code in R from scratch without using any predefined functions. But I am getting an error message saying-

In complex(real = rl, imaginary = hig) : imaginary parts discarded in coercion

I think that means complex numbers can't be stored in vectors.

Please tell me whether I am right or wrong and also please help me to solve this error.

Below is my code.

listx=c()
z=0
inmbs=F
imgdispl=matrix(c(),441 ,441 )
for (hig in seq(-220,220,1)){
  for (wid in seq(-220,220,1)){
    listx=c()
    z=0
    for (k in 0:5){
      inmbs=F
      xx=z^2
      rl=xx+wid
      l = complex(real = rl, imaginary = hig)
      if (l %in% listx){
        inmbs=T
        break
      }
      else{
        append(listx,l)
        z=l
      }
    }
    if (inmbs==T){
      imgdispl[hig+221,wid+221]=1
    }
    else{
      imgdispl[hig+221,wid+221]=0  
    }
  }
}
image(imgdispl)

updated code:

listx=c()
z=0
inmbs=F
imgdispl=matrix(c(0),441 ,441 )
for (hig in seq(-220,220,1)){
  for (wid in seq(-220,220,1)){
    listx=c()
    z=0
    for (k in 0:5){
      inmbs=F
      xx=z^2
      coor = complex(real = wid/15, imaginary = hig/15)
      l=xx+coor
      if (l %in% listx){
        inmbs=T
        break
      }
      else{
        append(listx,l)
        z=l
      }
    }
    if (inmbs==T){
      imgdispl[hig+221,wid+221]=1
    }
    else{
      imgdispl[hig+221,wid+221]=0  
    }
  }
}
image(imgdispl)

Upvotes: 0

Views: 133

Answers (1)

Waldi
Waldi

Reputation: 41220

If you debug your code you'll see that rl becomes complex.
The message tells you that only the real part is used in the call to:

l = complex(real = rl, imaginary = hig)

If you follow these instructions, you get:

z=0
N=10
inmbs=F
imgdispl=matrix(c(0),441 ,441 )
for (hig in seq(-220,220,1)){
  for (wid in seq(-220,220,1)){
    coor = complex(real = wid/220, imaginary = hig/220)
    z=0
    
    for (k in 0:N){
      inmbs=F
      if ((Re(z)^2+Im(z)^2)>4){
        inmbs=T
        break
      }
    z = z^2 + coor
    }
    if (inmbs==T){
      imgdispl[hig+221,wid+221]=1
    }
    else{
      imgdispl[hig+221,wid+221]=0  
    }
  }
}
image(imgdispl)

enter image description here

Upvotes: 1

Related Questions