⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 01 - comparing floating-point numbers.rb

📁 O Reilly Ruby Cookbook source code
💻 RB
字号:
1.8 + 0.1                                  # => 1.91.8 + 0.1 == 1.9                           # => false1.8 + 0.1 > 1.9                            # => true#---class Float  def approx(other, relative_epsilon=Float::EPSILON, epsilon=Float::EPSILON)    difference = other - self    return true if difference.abs <= epsilon    relative_error = (difference / (self > other ? self : other)).abs    return relative_error <= relative_epsilon  endend100.2.approx(100.1 + 0.1)               # => true10e10.approx(10e10+1e-5)                # => true100.0.approx(100+1e-5)                  # => false#---printf("%.55f", 1.9)# 1.8999999999999999111821580299874767661094665527343750000printf("%.55f", 1.8 + 0.1)# 1.9000000000000001332267629550187848508358001708984375000#---Float::EPSILON                            # => 2.22044604925031e-16(1.8 + 0.1) - 1.9                         # => 2.22044604925031e-16#---class Float  def absolute_approx(other, epsilon=Float::EPSILON)    puts((other-self).abs)    return (other-self).abs <= epsilon  endend(1.8 + 0.1).absolute_approx(1.9)               # => true10e10.absolute_approx(10e10+1e-5)              # => false#---98.6.approx(98.66)                           # => false98.6.approx(98.66, 0.001)                    # => true#---

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -