首页 web前端 js教程 Beyond JavaScript - Why + doesn&#t equal in programming

Beyond JavaScript - Why + doesn&#t equal in programming

Sep 13, 2024 pm 10:17 PM

JavaScript is frequently ridiculed when developers first encounter this seemingly baffling result:

0.1 + 0.2 == 0.30000000000000004

Memes about JavaScript's handling of numbers are widespread, often leading many to believe that this behaviour is unique to the language.

Beyond JavaScript - Why  +  doesn

However, this quirk isn't just limited to JavaScript. It is a consequence of how most programming languages handle floating-point arithmetic.

For instance, here are code snippets from Java and Go that produce similar results:

Beyond JavaScript - Why  +  doesn

Beyond JavaScript - Why  +  doesn

Computers can natively only store integers. They don't understand fractions. (How will they? The only way computers can do arithmetic is by turning some lights on or off. The light can either be on or off. It can't be "half" on!) They need some way of representing floating point numbers. Since this representation is not perfectly accurate, more often than not, 0.1 + 0.2 does not equal 0.3.

All fractions whose denominators are made of prime factors of the number system's base can be cleanly expressed while any other fractions would have repeating decimals. For example, in the number system with base 10, fractions like 1/2, 1/4, 1/5, 1/10 are cleanly represented because the denominators in each case are made up of 2 or 5 - the prime factors of 10. However, fractions like 1/3, 1/6, 1/7 all have recurring decimals.

Similarly, in the binary system fractions like 1/2, 1/4, 1/8 are cleanly expressed while all other fractions have recurring decimals. When you perform arithmetic on these recurring decimals, you end up with leftovers which carry over when you convert the computer's binary representation of numbers to a human readable base-10 representation. This is what leads to approximately correct results.

Now that we've established that this problem is not exclusive to JavaScript, let's explore how floating-point numbers are represented and processed under the hood to understand why this behaviour occurs.

In order to understand how floating point numbers are represented and processed under the hood, we would first have to understand the IEEE 754 floating point standard.

IEEE 754 standard is a widely used specification for representing and performing arithmetic on floating-point numbers in computer systems. It was created to guarantee consistency when using floating-point arithmetic on various computing platforms. Most programming languages and hardware implementations (CPUs, GPUs, etc.) adhere to this standard.

This is how a number is denoted in IEEE 754 format:

Beyond JavaScript - Why  +  doesn

Here s is the sign bit (0 for positive, 1 for negative), M is the mantissa (holds the digits of the number) and E is the exponent which determines the scale of the number.

You would not be able to find any integer values for M and E that can exactly represent numbers like 0.1, 0.2 or 0.3 in this format. We can only pick values for M and E that give the closest result.

Here is a tool you could use to determine the IEEE 754 notations of decimal numbers: https://www.h-schmidt.net/FloatConverter/IEEE754.html

IEEE 754 notation of 0.25:

Beyond JavaScript - Why  +  doesn

IEEE 754 notation of 0.1 and 0.2 respectively:

Beyond JavaScript - Why  +  doesn
Beyond JavaScript - Why  +  doesn

Please note that the error due to conversion in case of 0.25 was 0, while 0.1 and 0.2 had non-zero errors.

IEEE 754 defines the following formats for representing floating-point numbers:

  • Single-precision (32-bit): 1 bit for sign, 8 bits for exponent, 23 bits for mantissa

  • Double-precision (64-bit): 1 bit for sign, 11 bits for exponent, 52 bits for mantissa

For the sake of simplicity, let us consider the single-precision format that uses 32 bits.

The 32 bit representation of 0.1 is:

0 01111011 10011001100110011001101

Here the first bit represents the sign (0 which means positive in this case), the next 8 bits (01111011) represent the exponent and the final 23 bits (10011001100110011001101) represent the mantissa.

This is not an exact representation. It represents ≈ 0.100000001490116119384765625

Similarly, the 32 bit representation of 0.2 is:

0 01111100 10011001100110011001101

This is not an exact representation either. It represents ≈ 0.20000000298023223876953125

When added, this results in:

0 01111101 11001101010011001100110 

which is ≈ 0.30000001192092896 in decimal representation.

In conclusion, the seemingly perplexing result of 0.1 + 0.2 not yielding 0.3 is not an anomaly specific to JavaScript, but a consequence of the limitations of floating-point arithmetic across programming languages. The roots of this behaviour lie in the binary representation of numbers, which inherently leads to precision errors when handling certain fractions.

以上是Beyond JavaScript - Why + doesn&#t equal in programming的详细内容。更多信息请关注PHP中文网其他相关文章!

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热AI工具

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

热门话题

PHP教程
1545
276
高级JavaScript范围和上下文 高级JavaScript范围和上下文 Jul 24, 2025 am 12:42 AM

JavaScript的作用域决定变量可访问范围,分为全局、函数和块级作用域;上下文决定this的指向,依赖函数调用方式。1.作用域包括全局作用域(任何地方可访问)、函数作用域(仅函数内有效)、块级作用域(let和const在{}内有效)。2.执行上下文包含变量对象、作用域链和this的值,this在普通函数指向全局或undefined,在方法调用指向调用对象,在构造函数指向新对象,也可用call/apply/bind显式指定。3.闭包是指函数访问并记住外部作用域变量,常用于封装和缓存,但可能引发

掌握JavaScript并发模式:网络工人与Java线程 掌握JavaScript并发模式:网络工人与Java线程 Jul 25, 2025 am 04:31 AM

JavaScript的WebWorkers和JavaThreads在并发处理上有本质区别。1.JavaScript采用单线程模型,WebWorkers是浏览器提供的独立线程,适合执行不阻塞UI的耗时任务,但不能操作DOM;2.Java从语言层面支持真正的多线程,通过Thread类创建,适用于复杂并发逻辑和服务器端处理;3.WebWorkers使用postMessage()与主线程通信,安全隔离性强;Java线程可共享内存,需注意同步问题;4.WebWorkers更适合前端并行计算,如图像处理,而

VUE 3组成API与选项API:详细比较 VUE 3组成API与选项API:详细比较 Jul 25, 2025 am 03:46 AM

Vue3中CompositionAPI更适合复杂逻辑和类型推导,OptionsAPI适合简单场景和初学者;1.OptionsAPI按data、methods等选项组织代码,结构清晰但复杂组件易碎片化;2.CompositionAPI用setup集中相关逻辑,利于维护和复用;3.CompositionAPI通过composable函数实现无冲突、可参数化的逻辑复用,优于mixin;4.CompositionAPI对TypeScript支持更好,类型推导更精准;5.两者性能和打包体积无显着差异;6.

用node.js构建CLI工具 用node.js构建CLI工具 Jul 24, 2025 am 03:39 AM

初始化项目并创建package.json;2.创建带shebang的入口脚本index.js;3.在package.json中通过bin字段注册命令;4.使用yargs等库解析命令行参数;5.用npmlink本地测试;6.添加帮助、版本和选项增强体验;7.可选地通过npmpublish发布;8.可选地用yargs实现自动补全;最终通过合理结构和用户体验设计打造实用的CLI工具,完成自动化任务或分发小工具,以完整句⼦结束。

如何在JS中创建和附加元素? 如何在JS中创建和附加元素? Jul 25, 2025 am 03:56 AM

使用document.createElement()创建新元素;2.通过textContent、classList、setAttribute等方法自定义元素;3.使用appendChild()或更灵活的append()方法将元素添加到DOM中;4.可选地使用insertBefore()、before()等方法控制插入位置;完整流程为创建→自定义→添加,即可动态更新页面内容。

在打字稿中的高级条件类型 在打字稿中的高级条件类型 Aug 04, 2025 am 06:32 AM

TypeScript的高级条件类型通过TextendsU?X:Y语法实现类型间的逻辑判断,其核心能力体现在分布式条件类型、infer类型推断和复杂类型工具的构建。1.条件类型在裸类型参数上具有分布性,能自动对联合类型拆分处理,如ToArray得到string[]|number[]。2.利用分布性可构建过滤与提取工具:Exclude通过TextendsU?never:T排除类型,Extract通过TextendsU?T:never提取共性,NonNullable过滤null/undefined。3

微观前端体系结构:实施指南 微观前端体系结构:实施指南 Aug 02, 2025 am 08:01 AM

Microfrontendssolvescalingchallengesinlargeteamsbyenablingindependentdevelopmentanddeployment.1)Chooseanintegrationstrategy:useModuleFederationinWebpack5forruntimeloadingandtrueindependence,build-timeintegrationforsimplesetups,oriframes/webcomponents

Jul 26, 2025 am 07:52 AM

要获取JavaScript数组的长度,可以使用内置的length属性。1.使用.length属性可返回数组中元素的数量,例如constfruits=['apple','banana','orange'];console.log(fruits.length);//输出:3;2.该属性适用于包含字符串、数字、对象或数组等任何类型数据的数组;3.length属性会自动更新,当添加或删除元素时其值随之变化;4.它返回基于零的计数,空数组的length为0;5.可手动修改length属性来截断或扩展数组,

See all articles