检查溢出

基本类型 / 数字 / 整型

# 没有 byte 类型:不会回绕成 44
b1 <- 200L
b2 <- 100L
b3 <- b1 + b2
# b3 = 300

# integer 的 32 位上限
max_int <- .Machine$integer.max
# max_int = 2147483647

# 双精度数范围更大,不会溢出
a <- max_int + 1
# a = 2147483648

# 有意回绕,只保留 8 位
wrapped <- b3 %% 256L
# wrapped = 44

# 固定宽度,需自行检查范围
fits_byte <- b3 >= 0L && b3 <= 255L
# fits_byte = FALSE

# 整数溢出:得到 NA,不会回绕
overflow <- suppressWarnings(max_int + 1L)
# overflow = NA

cat("b3 =", b3, "\n")
cat("max_int =", max_int, "\n")
cat("a =", a, "\n")
cat("wrapped =", wrapped, "\n")
cat("fits_byte =", fits_byte, "\n")
cat("overflow =", overflow, "\n")

# 得到 NA 的同时会给出警告
msg <- tryCatch(max_int + 1L,
                warning = conditionMessage)
cat("msg =", msg, "\n")
# msg = NAs produced by integer overflow