- Perl 6 Deep Dive
- Andrew Shitov
- 396字
- 2021-07-03 00:05:51
Rational data type
In Perl 6, a special type Rat exists to store the rational numbers. In many cases, Rat will be used when you deal with floating-point numbers. Internally, the Rat value is represented by a pair of integer values, numerators, and denominators. Thus, any Rat number is a rational value equal to the division N/D. The integer numerator part is a value that can be arbitrarily long. The denominator part is a 64-bit integer.
Rat values appear as soon as you have a constant with the decimal point without an exponential part. Consider the following example:
say 3.14;
The 3.14 literal creates a Rat value here.
There is another syntax to create a Rat value: use the slash as in division and, optionally, enclose a number in the pair of angle brackets, as shown here:
say 1/2;
say <1/2>;
Also, you may use Unicode characters for fractions. For example, the following line will create a Rat number equal to 0.5:
say ?;
The internal structure of Rat values provides a fantastic ability for precise calculations. Unlike many other languages, where a floating-point arithmetic uses the IEEE numbers with limited precision, in Perl 6, the use of Rat numbers helps to avoid rounding errors when working with small numbers or, for example, with two numbers so close to each other that they cannot be compared precisely using the IEEE representations.
In the following examples, we will use the Rat numbers:
say 1/2 + 1/4 + 1/8 + 1/16;
say 0.1 + 0.2 - 0.3;
The last example is interesting because it prints 0 in Perl 6. Perl 6 uses Rat for calculations, and internally treats the values as 1/10, 2/10, and 3/10. Thus, the full sum of 0.1 + 0.2 - 0.3 is equivalent to 1/10 + 2/10 - 3/10, which results in a Rat value of 0/10, which is zero. In many other languages that use floating-point numbers, including Perl 5, the same calculation will not produce zero. The result would be small, but still non-zero; for example, 5.55111512312578e-17.
The advantage of using Rat for precise calculations is obvious. For example, in financial calculations, you may use Rat numbers to avoid rounding errors. (In many cases, though, in the financial calculation, you may use integers and count in cents; so, instead of keeping 9.99 € as a floating-point number, operate with 999 cents instead.)
- Python程序設計教程(第2版)
- 國際大學生程序設計競賽中山大學內(nèi)部選拔真題解(二)
- Java入門經(jīng)典(第6版)
- RTC程序設計:實時音視頻權威指南
- CKA/CKAD應試教程:從Docker到Kubernetes完全攻略
- Access 2016數(shù)據(jù)庫管
- VMware虛擬化技術
- 執(zhí)劍而舞:用代碼創(chuàng)作藝術
- Service Mesh實戰(zhàn):基于Linkerd和Kubernetes的微服務實踐
- Visual Foxpro 9.0數(shù)據(jù)庫程序設計教程
- ASP.NET求職寶典
- Learn Linux Quickly
- Swift 2 Design Patterns
- 3D Printing Designs:Design an SD Card Holder
- 高性能MVVM框架的設計與實現(xiàn):San