A pitfall in R
先看下面的代码:
1 2 3 4 | freq <- 0.29 altAllele <- freq * 200 * 2 print (altAllele) ## this will output 116 print ( length ( rep (1, altAllele))) ## what is the output of this?? |
最后一行输出的是115, 不是116。为什么?
答案是:
altAllele是一个numeric类型的数,尽管打印出来是116,但在电脑里存储的是一个比整数116稍小的浮点数。因此rep(1, altAllele)是一个长度是115的vector。
R的程序有很多陷阱。这个陷阱是因为R不需要定义数据类型,但它的底层还是有类型的。因此写R程序一定要注意这点。解决方法如下:
1 2 3 4 | freq <- 0.29 altAllele <- as.integer (freq * 200 * 2) print (altAllele) ## this will output 116 print ( length ( rep (1, altAllele))) ## what is the output of this?? |
Python里有没有类似的陷阱?结论是一样有 (Python 2.7.5 NumPy 1.8.0):
1 2 3 | freq = .29 altAllele = freq * 200 * 2 len ( np.repeat (1, altAllele)) ## output 115 here. |
但是Python里打印altAllele的值不是116,而是115.99999999999999。这总比R打印出16要好一点。