You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用R语言计算两个数字小数点后相同的位数

R语言:统计两个数字小数点后相同的位数

嘿,我来给你写个靠谱的R函数,专门搞定统计两个数字小数点后相同位数的需求,还考虑了各种边界情况——比如其中一个是整数、小数部分长度不一样这些场景,直接能用:

count_same_decimal_digits <- function(num1, num2) {
  # 把数字转成字符串,避免科学计数法,保留足够多的小数位防止丢失信息
  str1 <- format(num1, scientific = FALSE, digits = 20)
  str2 <- format(num2, scientific = FALSE, digits = 20)
  
  # 拆分整数和小数部分(点号需要转义,所以用\\.)
  parts1 <- strsplit(str1, "\\.", fixed = FALSE)[[1]]
  parts2 <- strsplit(str2, "\\.", fixed = FALSE)[[1]]
  
  # 提取小数部分,如果数字是整数(没有小数点),就设为空字符串
  dec1 <- if (length(parts1) == 2) parts1[2] else ""
  dec2 <- if (length(parts2) == 2) parts2[2] else ""
  
  same_count <- 0
  max_compare_len <- min(nchar(dec1), nchar(dec2))
  
  # 逐位对比小数部分,遇到不同的位就停止
  for (i in 1:max_compare_len) {
    if (substr(dec1, i, i) == substr(dec2, i, i)) {
      same_count <- same_count + 1
    } else {
      break
    }
  }
  
  # 输出要求的格式
  cat(paste(same_count, "digits are the same\n"))
}

函数说明&测试案例

我给你几个测试场景,看看效果:

  • 完全相同的小数部分
count_same_decimal_digits(123.4567890123, 123.4567890123)
# 输出:10 digits are the same
  • 部分相同的小数
count_same_decimal_digits(1.23456, 1.23478)
# 输出:3 digits are the same
  • 其中一个是整数
count_same_decimal_digits(5, 5.0000)
# 输出:4 digits are the same
  • 小数部分长度不同
count_same_decimal_digits(3.1415, 3.1415926)
# 输出:4 digits are the same

小提示

  • 用format()函数是为了避免R把大数字自动转成科学计数法,确保我们能拿到完整的小数位字符串
  • 循环会在遇到第一个不同的位时立刻停止,不会做多余的计算,效率还不错

内容的提问来源于stack exchange,提问作者Lorenzo Negri

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 09:08:46