posterior icon indicating copy to clipboard operation
posterior copied to clipboard

Support for complex numbers

Open mjskay opened this issue 2 years ago • 0 comments
trafficstars

After seeing @WardBrian's comment here: https://github.com/stan-dev/posterior/issues/317#issuecomment-1817035410

it occurred to me to check our support for complex numbers. It appears none of the existing formats support them.

Support for converting complex numbers that are encoded as arrays with a dimension that has a "real" and "complex" component would be straightforward if our underlying types worked with R's complex number data type; e.g. given a variable like this:

> cbind(real = rvar_rng(rnorm, 5), imag = rvar_rng(rnorm, 5, 1))
rvar<4000>[5,2] mean ± sd:
     real            imag           
[1,] -0.0069 ± 1.01   0.9964 ± 1.02 
[2,] -0.0093 ± 0.99   0.9854 ± 0.98 
[3,] -0.0061 ± 1.02   0.9984 ± 0.99 
[4,]  0.0301 ± 0.99   0.9650 ± 1.00 
[5,]  0.0030 ± 1.00   0.9919 ± 0.99 

The following would be an easy way to turn the above into a complex rvar backed by the base complex number data type if it wasn't generating a bunch of warnings:

> x = cbind(real = rvar_rng(rnorm, 5), imag = rvar_rng(rnorm, 5, 1))
> x[,"real"] + x[,"imag"] * rvar(1i)
rvar<4000>[5,1] mean ± sd:
     real            
[1,] -0.02+0.99i ± 1 
[2,]  0.00+1.00i ± 1 
[3,]  0.00+1.02i ± 1 
[4,]  0.00+1.00i ± 1 
[5,]  0.02+1.00i ± 1 
Warning messages:
1: In var(if (is.vector(x) || is.factor(x)) x else as.double(x), na.rm = na.rm) :
  imaginary parts discarded in coercion
2: In var(if (is.vector(x) || is.factor(x)) x else as.double(x), na.rm = na.rm) :
  imaginary parts discarded in coercion
3: In var(if (is.vector(x) || is.factor(x)) x else as.double(x), na.rm = na.rm) :
  imaginary parts discarded in coercion
4: In var(if (is.vector(x) || is.factor(x)) x else as.double(x), na.rm = na.rm) :
  imaginary parts discarded in coercion
5: In var(if (is.vector(x) || is.factor(x)) x else as.double(x), na.rm = na.rm) :
  imaginary parts discarded in coercion

The other draws types all exhibit similar issues. Should be solvable though I think.

mjskay avatar Nov 18 '23 04:11 mjskay