Floating Point Math

Your language isn't broken, it's doing floating point math. Computers can only natively store integers, so they need some way of representing decimal numbers. This representation comes with some degree of inaccuracy. That's why, more often than not, .1 + .2 != .3.

Why does this happen?

It's actually pretty simple. When you have a base 10 system (like ours), it can only express fractions that use a prime factor of the base. The prime factors of 10 are 2 and 5. So 1/2, 1/4, 1/5, 1/8, and 1/10 can all be expressed cleanly because the denominators all use prime factors of 10. In contrast, 1/3, 1/6, and 1/7 are all repeating decimals because their denominators use a prime factor of 3 or 7. In binary (or base 2), the only prime factor is 2. So you can only express fractions cleanly which only contain 2 as a prime factor. In binary, 1/2, 1/4, 1/8 would all be expressed cleanly as decimals. While, 1/5 or 1/10 would be repeating decimals. So 0.1 and 0.2 (1/10 and 1/5) while clean decimals in a base 10 system, are repeating decimals in the base 2 system the computer is operating in. When you do math on these repeating decimals, you end up with leftovers which carry over when you convert the computer's base 2 (binary) number into a more human readable base 10 number.

Below are some examples of sending .1 + .2 to standard output in a variety of languages.

read more: | wikipedia | IEEE 754 | Stack Overflow | What Every Computer Scientist Should Know About Floating-Point Arithmetic

Language Code Result
ABAP
WRITE / CONV f( '.1' + '.2' ).

And

WRITE / CONV decfloat16( '.1' + '.2' ).

0.30000000000000004

And

0.3

Ada
with Ada.Text_IO; use Ada.Text_IO;
procedure Sum is
A : Float := 0.1;
B : Float := 0.2;
C : Float := A + B;
begin
Put_Line(Float'Image(C));
Put_Line(Float'Image(0.1 + 0.2));
end Sum;

3.00000E-01

3.00000E-01

APL
0.1 + 0.2

0.30000000000000004

AutoHotkey
MsgBox, % 0.1 + 0.2

0.300000

awk
echo | awk '{ print 0.1 + 0.2 }'

0.3

bc
0.1 + 0.2

0.3

C
#include<stdio.h>
int main(int argc, char** argv) {
printf("%.17f\n", .1+.2);
return 0;
}

0.30000000000000004

Clojure
(+ 0.1 0.2)

0.30000000000000004

Clojure supports arbitrary precision and ratios. (+ 0.1M 0.2M) returns 0.3M, while (+ 1/10 2/10) returns 3/10.

ColdFusion
<cfset foo = .1 + .2>
<cfoutput>#foo#</cfoutput>

0.3

Common Lisp
(+ .1 .2)

And

(+ 1/10 2/10)

And

(+ 0.1d0 0.2d0)

And

(- 1.2 1.0)

0.3

And

3/10

And

0.30000000000000004d0

And

0.20000005

CL’s spec doesn’t actually even require radix 2 floats (let alone specifically 32-bit singles and 64-bit doubles), but the high-performance implementations all seem to use IEEE floats with the usual sizes. This was tested on SBCL and ECL in particular.

C++
#include <iomanip>
std::cout << std::setprecision(17) << 0.1 + 0.2

0.30000000000000004

Crystal
puts 0.1 + 0.2

And

puts 0.1_f32 + 0.2_f32

0.30000000000000004

And

0.3

C#
Console.WriteLine("{0:R}", .1 + .2);

And

Console.WriteLine("{0:R}", .1m + .2m);

0.30000000000000004

And

0.3

C# has support for 128-bit decimal numbers, with 28-29 significant digits of precision. Their range, however, is smaller than that of both the single and double precision floating point types. Decimal literals are denoted with the m suffix.

D
import std.stdio;

void main(string[] args) {
writefln("%.17f", .1+.2);
writefln("%.17f", .1f+.2f);
writefln("%.17f", .1L+.2L);
}

0.29999999999999999

0.30000001192092896

0.30000000000000000

Dart
print(.1 + .2);

0.30000000000000004

dc
0.1 0.2 + p

.3

Delphi XE5
writeln(0.1 + 0.2);

3.00000000000000E-0001

Elixir
IO.puts(0.1 + 0.2)

0.30000000000000004

Elm
0.1 + 0.2

0.30000000000000004

elvish
+ .1 .2

0.30000000000000004

elvish uses Go’s double for numerical operations.

Emacs Lisp
(+ .1 .2)

0.30000000000000004

Erlang
io:format("~w~n", [0.1 + 0.2]).

0.30000000000000004

FORTRAN
program FLOATMATHTEST
real(kind=4) :: x4, y4
real(kind=8) :: x8, y8
real(kind=16) :: x16, y16
! REAL literals are single precision, use _8 or _16
! if the literal should be wider.
x4 = .1; x8 = .1_8; x16 = .1_16
y4 = .2; y8 = .2_8; y16 = .2_16
write (*,*) x4 + y4, x8 + y8, x16 + y16
end

0.300000012

0.30000000000000004

0.300000000000000000000000000000000039

Gforth
0.1e 0.2e f+ f.

0.3

GHC (Haskell)
* 0.1 + 0.2 :: Double

And

* 0.1 + 0.2 :: Float

* 0.30000000000000004

And

* 0.3

Haskell supports rational numbers. To get the math right, 0.1 + 0.2 :: Rational returns 3 % 10, which is exactly 0.3.

Go
package main
import "fmt"
func main() {
fmt.Println(.1 + .2)
var a float64 = .1
var b float64 = .2
fmt.Println(a + b)
fmt.Printf("%.54f\n", .1 + .2)
}

0.3

0.30000000000000004

0.299999999999999988897769753748434595763683319091796875

Go numeric constants have arbitrary precision.

Groovy
println 0.1 + 0.2

0.3

Literal decimal values in Groovy are instances of java.math.BigDecimal

Hugs (Haskell)
0.1 + 0.2

0.3

Io
(0.1 + 0.2) print

0.3

Java
System.out.println(.1 + .2);

And

System.out.println(.1F + .2F);

0.30000000000000004

And

0.3

Java has built-in support for arbitrary precision numbers using the BigDecimal class.

JavaScript
console.log(.1 + .2);

0.30000000000000004

The decimal.js library provides an arbitrary-precision Decimal type for JavaScript.

Julia
.1 + .2

0.30000000000000004

Julia has built-in rational numbers support and also a built-in arbitrary-precision BigFloat data type. To get the math right, 1//10 + 2//10 returns 3//10.

K (Kona)
0.1 + 0.2

0.3

Lua
print(.1 + .2)

And

print(string.format("%0.17f", 0.1 + 0.2))

0.3

And

0.30000000000000004

Mathematica
0.1 + 0.2

0.3

Mathematica has a fairly thorough internal mechanism for dealing with numerical precision and supports arbitrary precision.

Matlab
0.1 + 0.2

And

sprintf('%.17f',0.1+0.2)

0.3

And

0.30000000000000004

MySQL
SELECT .1 + .2;

0.3

Nim
echo(0.1 + 0.2)

0.3

Objective-C
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[]) {
@autoreleasepool {
NSLog(@"%.17f\n", .1+.2);
}
return 0;
}

0.30000000000000004

OCaml
0.1 +. 0.2;;

float = 0.300000000000000044

Perl 5
perl -E 'say 0.1+0.2'

And

perl -e 'printf q{%.17f}, 0.1+0.2'

0.3

And

0.30000000000000004

Perl 6
perl6 -e 'say 0.1+0.2'

And

perl6 -e 'say (0.1+0.2).base(10, 17)'

And

perl6 -e 'say 1/10+2/10'

And

perl6 -e 'say (0.1.Num + 0.2.Num).base(10, 17)'

0.3

And

0.3

And

0.3

And

0.30000000000000004

Perl 6, unlike Perl 5, uses rationals by default, so .1 is stored something like { numerator => 1, denominator => 10 }. To actually trigger the behavior, you must force the numbers to be of type Num (double in C terms) and use the base function instead of the sprintf or fmt functions (since those functions have a bug that limits the precision of the output).

PHP
echo .1 + .2;
var_dump(.1 + .2);

0.3 float(0.30000000000000004441)

PHP echo converts 0.30000000000000004441 to a string and shortens it to “0.3”. To achieve the desired floating point result, adjust the precision ini setting: ini_set(“precision”, 17).

PicoLisp
[load "frac.min.l"]  # https://gist.github.com/6016d743c4c124a1c04fc12accf7ef17

And

[println (+ (/ 1 10) (/ 2 10))]

(/ 3 10)

You must load file “frac.min.l”.

Postgres
SELECT select 0.1::float + 0.2::float;

0.3

Powershell
PS C:\>0.1 + 0.2

0.3

Prolog (SWI-Prolog)
?- X is 0.1 + 0.2.

X = 0.30000000000000004.

Pyret
0.1 + 0.2

And

~0.1 + ~0.2

0.3

And

~0.30000000000000004

Pyret has built-in support for both rational numbers and floating points. Numbers written normally are assumed to be exact. In contrast, RoughNums are represented by floating points, and are written with a ~ in front, to indicate that they are not precise answers. (The ~ is meant to visually evoke hand-waving.) Therefore, a user who sees a computation produce ~0.30000000000000004knows to treat the value with skepticism. RoughNums also cannot be compared directly for equality; they can only be compared up to a given tolerance.

Python 2
print(.1 + .2)

And

.1 + .2

And

float(decimal.Decimal(".1") + decimal.Decimal(".2"))

And

float(fractions.Fraction('0.1') + fractions.Fraction('0.2'))

0.3

And

0.30000000000000004

And

0.3

And

0.3

Python 2’s “print” statement converts 0.30000000000000004 to a string and shortens it to “0.3”. To achieve the desired floating point result, use print(repr(.1 + .2)). This was fixed in Python 3 (see below).

Python 3
print(.1 + .2)

And

.1 + .2

And

float(decimal.Decimal('.1') + decimal.Decimal('.2'))

And

float(fractions.Fraction('0.1') + fractions.Fraction('0.2'))

0.30000000000000004

And

0.30000000000000004

And

0.3

And

0.3

Python (both 2 and 3) supports decimal arithmetic with the decimal module, and true rational numbers with the fractions module.

R
print(.1+.2)

And

print(.1+.2, digits=18)

0.3

And

0.30000000000000004

Racket (PLT Scheme)
(+ .1 .2)

And

(+ 1/10 2/10)

0.30000000000000004

And

3/10

Ruby
puts 0.1 + 0.2

And

puts 1/10r + 2/10r

0.30000000000000004

And

3/10

Ruby supports rational numbers in syntax with version 2.1 and newer directly. For older versions use Rational.

Ruby also has a library specifically for decimals: BigDecimal.

Rust
extern crate num;
use num::rational::Ratio;
fn main() {
println!("{}", 0.1 + 0.2);
println!("1/10 + 2/10 = {}", Ratio::new(1, 10) + Ratio::new(2, 10));
}

0.30000000000000004

And

1/10 + 2/10 = 3/10

Rust has rational number support from the num crate.

SageMath
.1 + .2

And

RDF(.1) + RDF(.2)

And

RBF('.1') + RBF('.2')

And

QQ('1/10') + QQ('2/10')

0.3

And

0.30000000000000004

And

[“0.300000000000000 +/- 1.64e-16”]

And

3/10

SageMath supports various fields for arithmetic: Arbitrary Precision Real NumbersRealDoubleFieldBall ArithmeticRational Numbers, etc.

scala
scala -e 'println(0.1 + 0.2)'

And

scala -e 'println(0.1F + 0.2F)'

And

scala -e 'println(BigDecimal("0.1") + BigDecimal("0.2"))'

0.30000000000000004

And

0.3

And

0.3

Smalltalk
0.1 + 0.2.

0.30000000000000004

Swift
0.1 + 0.2

And

NSString(format: "%.17f", 0.1 + 0.2)

0.3

And

0.30000000000000004

TCL
puts [expr .1 + .2]

0.30000000000000004

Turbo Pascal 7.0
writeln(0.1 + 0.2);

3.0000000000E-01

Vala
static int main(string[] args) {
stdout.printf("%.17f\n", 0.1 + 0.2);
return 0;
}

0.30000000000000004

Visual Basic 6
a# = 0.1 + 0.2: b# = 0.3
Debug.Print Format(a - b, "0." & String(16, "0"))
Debug.Print a = b

0.0000000000000001

False

Appending the identifier type character # to any identifier forces it to Double.

WebAssembly (WAST)
(func $add_f32 (result f32)
f32.const 0.1
f32.const 0.2
f32.add)
(export "add_f32" (func $add_f32))

And

(func $add_f64 (result f64)
f64.const 0.1
f64.const 0.2
f64.add)
(export "add_f64" (func $add_f64))

0.30000001192092896

And

0.30000000000000004

https://webassembly.studio/?f=r739k6d6q4t

zsh
echo "$((.1+.2))"

0.30000000000000004

I am Erik Wiffin. You can contact me at: erik.wiffin.com or erik.wiffin@gmail.com.

This project is on github. If you think this page could be improved, send me a pull request.

Floating Point Math的更多相关文章

  1. Brief Tour of the Standard Library

    10.1. Operating System Interface The os module provides dozens of functions for interacting with the ...

  2. Awk by Example--转载

    原文地址: http://www.funtoo.org/Awk_by_Example,_Part_1?ref=dzone http://www.funtoo.org/Awk_by_Example,_P ...

  3. C++ QUICK REFERENCE

    C++ string 用法详解 字符串分割(C++)  C++ QUICK REFERENCE Matt Mahoney, mmahoney@cs.fit.edu DECLARATIONS enum ...

  4. net programming guid

    Beej's Guide to Network Programming Using Internet Sockets Brian "Beej Jorgensen" Hallbeej ...

  5. VS2012下基于Glut 矩阵变换示例程序:

    也可以使用我们自己的矩阵运算来实现OpenGL下的glTranslatef相应的旋转变换.需要注意的是OpenGL下的矩阵是列优先存储的. 示例通过矩阵运算使得圆柱或者甜圈自动绕Y轴旋转,可以单击鼠标 ...

  6. [Python] 01 - Number

    故事背景 一.大纲 如下,chapter4 是个概览,之后才是具体讲解. 二. 编译过程 Ref: http://www.dsf.unica.it/~fiore/LearningPython.pdf

  7. JavaScript-Tool:Moment.js

    ylbtech-JavaScript-Tool:Moment.js Parse, validate, manipulate, and display dates and times in JavaSc ...

  8. Delphi 64与32位的差异

    Delphi 64与32位的差异   最近,Delphi推出了64位预览版本, 我做为一个忠实的Delphier, 看到这消息后,第一时间学习,并写下这个做为以后的参考资料. 相同点: 在Delphi ...

  9. [Python] 01 - Number and Matrix

    故事背景 一.大纲 如下,chapter4 是个概览,之后才是具体讲解. 二. 编译过程 Ref: http://www.dsf.unica.it/~fiore/LearningPython.pdf

随机推荐

  1. centos 防火墙 iptables firewalld SELinux

    参考 Centos7 只启用iptables 禁用firewalld功能 java.net.NoRouteToHostException: 没有到主机的路由 相关内容 centos7 中才开始引用fi ...

  2. 洛谷 P3388 【模板】割点(割顶)(Tarjan)

    题目链接 https://www.luogu.org/problemnew/show/P3388 模板题 解题思路 什么是割点? 怎样求割点? dfn :即时间戳,一张图的dfs序(dfs遍历时出现的 ...

  3. 小白学习django第二站-模版配置

    上一站说道app创建,接下来我们来配置app的url路由 首先需要到setting.py中添加book这个app, 再到django_test文件里的urls添加路由 include() : 这个函数 ...

  4. javaweb:Response/Request的概述 (转发、重定向、get/post)转

    请求响应流程图 1]response 1   response概述 response是Servlet.service方法的一个参数,类型为javax.servlet.http.HttpServletR ...

  5. PHP 数组辅助函数

    /** * 取多维数据中某字段的值 * @param array $array 数据源数组 * @param string|array $field 要获取的字段 * @return array 结果 ...

  6. Linux如何查看进程是否启动,查看端口占用

    Linux系统中经常需要查看某个进程是否已经启动,启动位置在哪里,某个端口是否被占用,被哪个进程占用等,这些都可以通过命令来完成,本文讲述如何查看进程是否启动,查看端口占用 1.通过ps -ef | ...

  7. Comet OJ - Contest #13 「佛御石之钵 -不碎的意志-」(hard)

    来源:Comet OJ - Contest #13 一眼并查集,然后发现这题 tmd 要卡常数的说卧槽... 发现这里又要用并查集跳过访问点,又要用并查集维护联通块,于是开俩并查集分别维护就好了 一开 ...

  8. icmp, IPPROTO_ICMP - Linux IPv4 ICMP 核心模块.

    DESCRIPTION 描述 本网络核心协议模块实现了基于 RFC792 协议中定义的<互联网控制报文协议>.它针对网络主机间通讯出错的情况作出回应并给出诊断信息.用户不能直接使用本模块. ...

  9. SpringMVC与Json数据交互

    简单回顾了一下SpringMVC和前端JSON数据是怎么交互的 接下来详细说一下过程 前端代码写的很简单  主要是为了试验一下JSON数据的前后台传递 前端代码给大家发出来 其实真的很简单 前端接受了 ...

  10. Python-Django的windows环境

    下载安装python2.7 : 最好是安装win32的,64bit的很多的lib都不支持.python-2.7.3 http://python.org/getit/releases/2.7.3/ 下载 ...