Floating point in sCrypt

This post originally appeared on Medium, and we republished with permission from Xiaohui Liu.

sCrypt does not support floating point natively, mainly due to the high overhead of implementing it (such as IEEE Floating Point Standard) using integral arithmetic in Bitcoin Script. However, there are many use cases where fractional numbers are indispensable. We provide two libraries to support such cases.

Fixed Point Arithmetic

One simple way to represent a fractional number is storing a fixed number of digits of their fractional part, by scaling it with a fixed factor. For example, when you divide integer 1 by integer 2 in sCrypt, normally you get zero:

1 / 2 = 0

By scaling them both by 10 using fixed point, you get 5, which is 0.5 as expected:

10 * 10 / 20 = 5

The following library supports fixed point numbers.

FixedPoint Library
FixedPoint Library

Thanks to Bitcoin Virtual Machine’s native support of bigint of arbitrary length, it is extremely straightforward to implement fixed point of arbitrary precision. There is no overflow or underflow. Here is an example of using it.

Floating Point Arithmetic

In cases where high precision needs to be maintained throughout many consecutive steps of calculation, the following floating point library is preferred. It achieves accuracy at the cost of performance. A number is stored as n / d.

Floating Point Library
Floating Point Library

An example of using it can be found here.

New to Bitcoin? Check out CoinGeek’s Bitcoin for Beginners section, the ultimate resource guide to learn more about Bitcoin—as originally envisioned by Satoshi Nakamoto—and blockchain.

[10]
[10]
[id^="_form"]
[id^="_form"]
[id$="_submit"]
[id$="_submit"]
[^;]
[^;]
['on' + event]
['on' + event]
[?&]
[?&]
[^&#]
[^&#]
[(d+)]
[(d+)]
[i]
[i]
[results[1]]
[results[1]]
[elem.name]
[elem.name]
[+_a-z0-9-'&=]
[+_a-z0-9-'&=]
[+_a-z0-9-']
[+_a-z0-9-']
[a-z0-9-]
[a-z0-9-]
[a-z]
[a-z]
[el.name]
[el.name]
[10]
[10]
[id^="_form"]
[id^="_form"]
[id$="_submit"]
[id$="_submit"]
[^;]
[^;]
['on' + event]
['on' + event]
[?&]
[?&]
[^&#]
[^&#]
[(d+)]
[(d+)]
[i]
[i]
[results[1]]
[results[1]]
[elem.name]
[elem.name]
[+_a-z0-9-'&=]
[+_a-z0-9-'&=]
[+_a-z0-9-']
[+_a-z0-9-']
[a-z0-9-]
[a-z0-9-]
[a-z]
[a-z]
[el.name]
[el.name]