Home Web Front-end JS Tutorial Learn javascript floating point precision with me_javascript skills

Learn javascript floating point precision with me_javascript skills

May 16, 2016 pm 03:32 PM
javascript floating point number

Most programming languages ​​have several numeric data types, but JavaScript has only one. You can use the typeof operator to check the type of a number. Regardless of whether they are integers or floating point numbers, JavaScript simply classifies them as numbers.

typeof 17; //number
typeof 98.6; //number
typeof -21.3; //number
Copy after login

In fact, all numbers in JavaScript are double-precision floating point numbers. These are 64-bit encoded numbers - "doubles" - specified by the IEEE754 standard. If this fact makes you wonder how JavaScript represents integers, remember that double-precision floating point numbers perfectly represent integers up to 53 digits of precision. All integers from –9 007 199 254 740 992 (–253) to 9 007 199 254 740 992 (253) are valid double-precision floating point numbers. So, despite the lack of obvious integer types in JavaScript, integer arithmetic is perfectly possible.
Most arithmetic operators can perform calculations using integers, real numbers, or a combination of both.

0.1 * 0.9; //0.19
-99 + 100; //1
21- 12.3; //8.7
2.5 /5; //0.5
21%8; //5
Copy after login

However, bit arithmetic operators are special. JavaScript does not directly operate on the operand as a floating point number, but implicitly converts it to a 32-bit integer before performing the operation. (To be precise, they are converted to 32-bit big-endian 2’s complement representation of integers.) Take the bitwise OR expression as an example:

8|1; //9
Copy after login

A seemingly simple expression actually requires several steps to complete the operation. As mentioned before, the numbers 8 and 1 in JavaScript are both double-precision floating point numbers. But they can also be represented as 32-bit integers, which are sequences of 32 bits 0 and 1. The integer 8 is represented as a 32-bit binary sequence as follows:

00000000000000000000000000001000

You can also use the toString method of the numeric type to view it yourself:

(8).toString(2) //"1000"

The parameter of the

toString method specifies its conversion base. This example is expressed in base 2 (i.e. binary). The resulting value omits the extra 0 (bits) on the left because they do not affect the final value.
The integer 1 is represented as a 32-bit binary as follows:

00000000000000000000000000000001

Bitwise OR expression combines two bit sequences. As long as any one of the two bits involved in the operation is 1, the bit in the operation result will be 1. The result expressed as a bit pattern is as follows:

00000000000000000000000000001001

This sequence represents the integer 9. You can use the standard library function parseInt to verify, also using base 2:

parseInt("1000", 2); //9
Copy after login

(Again, leading 0 bits are unnecessary as they do not affect the result of the operation.)
All bitwise operators work the same way. They convert the operands to integers, then perform operations using integer bit patterns, and finally convert the result to a standard JavaScript floating point number. Typically, the JavaScript engine needs to do some extra work to perform these conversions. Because the number is stored as a floating point number, it must be converted to an integer and then converted back to a floating point number. However, in some cases, arithmetic expressions or even variables can only be operated with integers, and optimizing compilers can sometimes infer these situations and store numbers as integers internally to avoid redundant conversions.

A final warning about floating point numbers is that you should always be wary of them. Floating point numbers may seem familiar, but they are notoriously imprecise. Even some seemingly simple arithmetic operations can produce incorrect results.

0.1 0.2; 0.300000000000004

Although the precision of 64 bits is quite high, double-precision floating point numbers can only represent a limited set of numbers, but cannot represent the entire set of real numbers. Floating point operations can only produce approximate results, rounded to the nearest representable real number. As you perform a series of operations, the results become less and less accurate as rounding errors accumulate. Rounding can also produce some unexpected deviations from the laws of arithmetic we normally expect. For example, real numbers satisfy the associative law, which means that for any real numbers x, y, z, (x y) z = x (y z) is always satisfied.

However, for floating point numbers, this is not always the case.

(0.1+0.2)+0.3; //0.60000000000000001
0.1+(0.2+ 0.3); //0.6

Copy after login

Floating point numbers trade off precision and performance. When we care about precision, be careful about the limitations of floating point numbers. An efficient solution is to use integer-valued arithmetic whenever possible, since integers are represented without rounding. When performing currency-related calculations, programmers often proportionally convert the value to the smallest monetary unit before performing the calculation, so that the calculation can be performed as an integer. For example, if the above calculation is in US dollars, then we can convert it to an integer representation of cents.

(10+20)+30; //60
10+ (20+30); //60
Copy after login

For integer operations, you don’t have to worry about rounding errors, but you still have to be careful that all calculations only apply to integers from –253 to 253.

Tips

  • JavaScript numbers are all double-precision floating point numbers.
  • Integers in JavaScript are just a subset of double-precision floating point numbers, not a separate data type
  • Bitwise operators treat numbers as 32-bit signed integers.

The above is the introduction of floating point numbers in JavaScript. We must always pay attention to the precision traps in floating point operations. I hope this article will be helpful to everyone's learning.

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

PHP floating point number rounding method PHP floating point number rounding method Mar 21, 2024 am 09:21 AM

This article will explain in detail the PHP floating point number rounding method. The editor thinks it is very practical, so I share it with you as a reference. I hope you can gain something after reading this article. PHP Floating Point Rounding Overview Floating point numbers are represented in computers as a decimal point followed by an exponent, however, they are often stored in approximations with a limited number of digits. When you need to round a floating point number to a specific precision, there are several ways to do it. Method 1. round() function The round() function rounds a floating point number to the nearest integer. It accepts floating point numbers and optional precision parameters. For example: $num=1.55;echoround($num);//Output: 2echoround($num,1)

Causes and avoidance strategies of PHP floating point calculation errors Causes and avoidance strategies of PHP floating point calculation errors Feb 27, 2024 pm 06:33 PM

As a popular server-side scripting language, PHP often encounters problems of loss of precision or calculation errors when performing floating-point calculations. These problems may affect the accuracy and stability of the program. This article will explore the causes of PHP floating point calculation errors, propose some avoidance strategies, and give specific code examples for reference. 1. Reasons for PHP floating-point calculation errors. In computers, floating-point numbers are represented in binary form, and binary cannot accurately represent all decimal decimals, which leads to the inaccuracy of floating-point numbers.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

See all articles