简体   繁体   中英

Avoid floating point zero when summing scaled set of numbers in R

I am rescaling a set of numbers and want to avoid getting a floating point zero for the sum of the rescaled numbers:

x <- c(-5, 1, 8)
y <- scale(x)
sum(y)
# [1] 1.249001e-16

Is there a way to around this to force the sum to zero? I do not care about precision beyond a three decimal places.

I think you should not just "switch" to integers at some point. The scaling was computed with floating point numbers and is therefore not 100% precise. Forcing some values to 0 would indicate a precision that is not available and should thus be avoided.

If you need to compare floating point values use isTRUE(all.equal(...)) as suggested by R documentation. https://stat.ethz.ch/R-manual/R-devel/library/base/html/all.equal.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM