R中的类型保留(复数,实数)平方根?

时间:2017-08-31 11:06:46

标签: r types complex-numbers square-root

(添加了可重复的示例)

sqrt(as.complex(c(4,9,-4,-9,16))) # 2+0i 3+0i 0+2i 0+3i 4+0i
class(sqrt(as.complex(c(4,9,-4,-9,16)))) # complex
sqrt(as.complex(c(4,9,-4,-9,16)))[1] # 2+0i
class(sqrt(as.complex(c(4,9,-4,-9,16)))[1]) # complex

所以,我想定义一个特定的平方根函数(sqrtT),它将保留其元素的真实性/复杂性。所以实际上,我想要这个:

sqrtT(as.complex(c(4,9,-4,-9,16))) # 2 3 0+2i 0+3i 4
class(sqrtT(as.complex(c(4,9,-4,-9,16)))) # complex
sqrtT(as.complex(c(4,9,-4,-9,16)))[1] # 2
class(sqrtT(as.complex(c(4,9,-4,-9,16)))[1]) # numeric
class(sqrtT(as.complex(c(4,9,-4,-9,16)))[3]) # complex

我做了什么:
我找到了这些工具:
1。

Re(sqrt(as.complex(c(4,9,-4,-9,16)))) # 2 3 0 0 4
Im(sqrt(as.complex(c(4,9,-4,-9,16)))) # 0 0 2 3 0

顺便说一句,它必须保持类型本身,即,当我说sqrtT(as.complex(c(4,9,-4,-9,16))) #= 2 3 0+2i 0+3i 4时,显示此输出(2 3 0+2i 0+3i 4),而实质上所有的复杂并不是我想要的。我的问题不仅仅是显示目的。

2. 有一种方法可以区分向量中元素的内容:

is.numeric(0+2i) # FALSE
is.numeric(2) # TRUE

3. 虚部的索引不等于0且等于0:

让向量为v。

v <- c(-1,4,9,-4,-9,0,16)
# The indices with imaginary part non-equal to 0 (IM<>0):
IMneq0 <- setdiff(which(as.numeric(sqrt(as.complex(v))) %in% 0),which(sqrt(as.complex(v))==0) )
IMneq0 # 1,4,5

# The indices with imaginary part equal to 0 (IM=0):
IMeq0 <- setdiff(1:length(sqrt(as.complex(v))),IMneq0 )
IMeq0 # 2 3 6 7

使用列表可以绕过对复合体的自动强制。

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

(一个糟糕的伪解决方案)

v <- c(-1,4,9,-4,-9,0,16)

sqrtTP <- function(v) { # Type preserving square root
IMne0 <- setdiff(which(as.numeric(sqrt(as.complex(v))) %in% 0),which(sqrt(as.complex(v))==0) )  #indices with imaginary part <> 0
IM0 <- setdiff(1:length(sqrt(as.complex(v))),IMne0 )   #indices with imaginary part =0
ValuesIM0 <- as.numeric(sqrt(as.complex(v[IM0]))) # values where IM=0
ValuesIMne0 <- sqrt(as.complex(v[IMne0])) # values where IM<>0
out <- list()
CounterIM0 <- 1 # counter where IM=0 coincided
CounterIMne0 <- 1 #  counter where IM<>0 coincided

for (i in as.integer(1:length(v))) {

if (i %in% IM0) {
out[[i]] <- ValuesIM0[CounterIM0]
CounterIM0 <- CounterIM0 +1
} else {
out[[i]] <- ValuesIMne0[CounterIMne0]
CounterIMne0 <- CounterIMne0 +1
}
}
out
}

sqrtTP(v)
# 0+1i  2   3  0+2i  0+3i   0  4  (given as list elements)
相关问题