Debian Codegraph @

www/floatingpoint.html

raw
1 <!DOCTYPE html>
2 <html><head>
3 <meta name="viewport" content="width=device-width, initial-scale=1.0">
4 <meta http-equiv="content-type" content="text/html; charset=UTF-8">
5 <link href="sqlite.css" rel="stylesheet">
6 <title>Floating Point Numbers</title>
7 <!-- path= -->
8 </head>
9 <body>
10 <div class=nosearch>
11 <a href="index.html">
12 <img class="logo" src="images/sqlite370_banner.gif" alt="SQLite" border="0">
13 </a>
14 <div><!-- IE hack to prevent disappearing logo --></div>
15 <div class="tagline desktoponly">
16 Small. Fast. Reliable.<br>Choose any three.
17 </div>
18 <div class="menu mainmenu">
19 <ul>
20 <li><a href="index.html">Home</a>
21 <li class='mobileonly'><a href="javascript:void(0)" onclick='toggle_div("submenu")'>Menu</a>
22 <li class='wideonly'><a href='about.html'>About</a>
23 <li class='desktoponly'><a href="docs.html">Documentation</a>
24 <li class='desktoponly'><a href="download.html">Download</a>
25 <li class='wideonly'><a href='copyright.html'>License</a>
26 <li class='desktoponly'><a href="support.html">Support</a>
27 <li class='desktoponly'><a href="prosupport.html">Purchase</a>
28 <li class='search' id='search_menubutton'>
29 <a href="javascript:void(0)" onclick='toggle_search()'>Search</a>
30 </ul>
31 </div>
32 <div class="menu submenu" id="submenu">
33 <ul>
34 <li><a href='about.html'>About</a>
35 <li><a href='docs.html'>Documentation</a>
36 <li><a href='download.html'>Download</a>
37 <li><a href='support.html'>Support</a>
38 <li><a href='prosupport.html'>Purchase</a>
39 </ul>
40 </div>
41 <div class="searchmenu" id="searchmenu">
42 <form method="GET" action="search">
43 <select name="s" id="searchtype">
44 <option value="d">Search Documentation</option>
45 <option value="c">Search Changelog</option>
46 </select>
47 <input type="text" name="q" id="searchbox" value="">
48 <input type="submit" value="Go">
49 </form>
50 </div>
51 </div>
52 <script>
53 function toggle_div(nm) {
54 var w = document.getElementById(nm);
55 if( w.style.display=="block" ){
56 w.style.display = "none";
57 }else{
58 w.style.display = "block";
59 }
60 }
61 function toggle_search() {
62 var w = document.getElementById("searchmenu");
63 if( w.style.display=="block" ){
64 w.style.display = "none";
65 } else {
66 w.style.display = "block";
67 setTimeout(function(){
68 document.getElementById("searchbox").focus()
69 }, 30);
70 }
71 }
72 function div_off(nm){document.getElementById(nm).style.display="none";}
73 window.onbeforeunload = function(e){div_off("submenu");}
74 /* Disable the Search feature if we are not operating from CGI, since */
75 /* Search is accomplished using CGI and will not work without it. */
76 if( !location.origin || !location.origin.match || !location.origin.match(/http/) ){
77 document.getElementById("search_menubutton").style.display = "none";
78 }
79 /* Used by the Hide/Show button beside syntax diagrams, to toggle the */
80 function hideorshow(btn,obj){
81 var x = document.getElementById(obj);
82 var b = document.getElementById(btn);
83 if( x.style.display!='none' ){
84 x.style.display = 'none';
85 b.innerHTML='show';
86 }else{
87 x.style.display = '';
88 b.innerHTML='hide';
89 }
90 return false;
91 }
92 var antiRobot = 0;
93 function antiRobotGo(){
94 if( antiRobot!=3 ) return;
95 antiRobot = 7;
96 var j = document.getElementById("mtimelink");
97 if(j && j.hasAttribute("data-href")) j.href=j.getAttribute("data-href");
98 }
99 function antiRobotDefense(){
100 document.body.onmousedown=function(){
101 antiRobot |= 2;
102 antiRobotGo();
103 document.body.onmousedown=null;
104 }
105 document.body.onmousemove=function(){
106 antiRobot |= 2;
107 antiRobotGo();
108 document.body.onmousemove=null;
109 }
110 setTimeout(function(){
111 antiRobot |= 1;
112 antiRobotGo();
113 }, 100)
114 antiRobotGo();
115 }
116 antiRobotDefense();
117 </script>
118 <div class=fancy>
119 <div class=nosearch>
120 <div class="fancy_title">
121 Floating Point Numbers
122 </div>
123 <div class="fancy_toc">
124 <a onclick="toggle_toc()">
125 <span class="fancy_toc_mark" id="toc_mk">&#x25ba;</span>
126 Table Of Contents
127 </a>
128 <div id="toc_sub"><div class="fancy-toc1"><a href="#how_sqlite_stores_numbers">1. How SQLite Stores Numbers</a></div>
129 <div class="fancy-toc2"><a href="#floating_point_accuracy">1.1. Floating-Point Accuracy</a></div>
130 <div class="fancy-toc2"><a href="#floating_point_numbers">1.2. Floating Point Numbers</a></div>
131 <div class="fancy-toc3"><a href="#unrepresentable_numbers">1.2.1. Unrepresentable numbers</a></div>
132 <div class="fancy-toc3"><a href="#is_it_close_enough_">1.2.2. Is it close enough?</a></div>
133 <div class="fancy-toc1"><a href="#extensions_for_dealing_with_floating_point_numbers">2. Extensions For Dealing With Floating Point Numbers</a></div>
134 <div class="fancy-toc2"><a href="#the_ieee754_c_extension">2.1. The ieee754.c Extension</a></div>
135 <div class="fancy-toc3"><a href="#the_ieee754_function">2.1.1. The ieee754() function</a></div>
136 <div class="fancy-toc3"><a href="#the_ieee754_mantissa_and_ieee754_exponent_functions">2.1.2. The ieee754_mantissa() and ieee754_exponent() functions</a></div>
137 <div class="fancy-toc3"><a href="#the_ieee754_from_blob_and_ieee754_to_blob_functions">2.1.3. The ieee754_from_blob() and ieee754_to_blob() functions</a></div>
138 <div class="fancy-toc2"><a href="#the_decimal_c_extension">2.2. The decimal.c Extension</a></div>
139 </div>
140 </div>
141 <script>
142 function toggle_toc(){
143 var sub = document.getElementById("toc_sub")
144 var mk = document.getElementById("toc_mk")
145 if( sub.style.display!="block" ){
146 sub.style.display = "block";
147 mk.innerHTML = "&#x25bc;";
148 } else {
149 sub.style.display = "none";
150 mk.innerHTML = "&#x25ba;";
151 }
152 }
153 </script>
154 </div>
155
156
157
158
159 <h1 id="how_sqlite_stores_numbers"><span>1. </span>How SQLite Stores Numbers</h1>
160
161 <p>
162 SQLite stores integer values in the 64-bit
163 <a href="https://en.wikipedia.org/wiki/Two%27s_complement">twos-complement</a>
164 format&sup1.
165 This gives a storage range of -9223372036854775808 to +9223372036854775807,
166 inclusive. Integers within this range are exact.
167
168 <a name="fpapprox"></a>
169
170 </p><p>
171 So-called "REAL" or floating point values are stored in the
172 <a href="https://en.wikipedia.org/wiki/IEEE_754">IEEE 754</a>
173 <a href="https://en.wikipedia.org/wiki/Double-precision_floating-point_format">Binary-64</a>
174 format&sup1.
175 This gives a range of positive values between approximately
176 1.7976931348623157e+308 and 4.9406564584124654e-324 with an equivalent
177 range of negative values. A binary64 can also be 0.0 (and -0.0), positive
178 and negative infinity and "NaN" or "Not-a-Number". Floating point
179 values are approximate.
180
181 </p><p>
182 Pay close attention to the last sentence in the previous paragraph:
183 </p><blockquote><b>
184 Floating point values are approximate.
185 </b></blockquote>
186
187 <p>
188 If you need an exact answer, you should not use binary64 floating-point
189 values, in SQLite or in any other product. This is not an SQLite limitation.
190 It is a mathematical limitation inherent in the design of floating-point numbers.
191
192 </p><p>&mdash;<br>&sup1;
193 Exception: The <a href="rtree.html">R-Tree extension</a> stores information as 32-bit floating
194 point or integer values.
195
196 </p><h2 id="floating_point_accuracy"><span>1.1. </span>Floating-Point Accuracy</h2>
197
198 <p>
199 SQLite promises to preserve the 15 most significant digits of a floating
200 point value. However, it makes no guarantees about the accuracy of
201 computations on floating point values, as no such guarantees are possible.
202 Performing math on floating-point values introduces error.
203 For example, consider what happens if you attempt to subtract two floating-point
204 numbers of similar magnitude:
205
206 </p><blockquote>
207 <table border="0" cellpadding="0" cellspacing="0">
208 <tr><td align="right">1152693165.1106291898</td></tr>
209 <tr><td align="right">-1152693165.1106280772</td></tr>
210 <tr><td><hr>
211 </td></tr><tr><td align="right">0.0000011126
212 </td></tr></table>
213 </blockquote>
214
215 <p>The result shown above (0.0000011126) is the correct answer. But if you
216 do this computation using binary64 floating-point, the answer you get is
217 0.00000095367431640625 - an error of about 14%. If you do many similar
218 computations as part of your program, the errors add up so that your final
219 result might be completely meaningless.
220
221 </p><p>The error arises because only about the first 15 significant digits of
222 each number are stored accurately, and the first difference between the two numbers
223 being subtracted is in the 16th digit.
224
225 </p><h2 id="floating_point_numbers"><span>1.2. </span>Floating Point Numbers</h2>
226
227 <p>
228 The binary64 floating-point format uses 64 bits per number. Hence there
229 are 1.845e+19 different possible floating point values. On the other hand
230 there are infinitely many real numbers in the range of
231 1.7977e+308 and 4.9407e-324. It follows then that binary64 cannot possibly
232 represent all possible real numbers within that range. Approximations are
233 required.
234
235 </p><p>
236 An IEEE 754 floating-point value is an integer multiplied by a power
237 of two:
238
239 </p><blockquote>
240 <big>M &times 2<sup><small>E</small></sup></big>
241 </blockquote>
242
243 <p>The M value is the "mantissa" and E is the "exponent". Both
244 M and E are integers.
245
246 </p><p>For Binary64, M is a 53-bit integer and E is an 11-bit integer that is
247 offset so that represents a range of values between -1074 and +972, inclusive.
248
249 </p><p><i>(NB: The usual description of IEEE 754 is more complex, and it is important
250 to understand the added complexity if you really want to appreciate the details,
251 merits, and limitations of IEEE 754. However, the integer description shown
252 here, while not exactly right, is easier to understand and is sufficient for
253 the purposes of this article.)</i></p>
254
255 <h3 id="unrepresentable_numbers"><span>1.2.1. </span>Unrepresentable numbers</h3>
256
257 <p>Not every decimal number with fewer than 16 significant digits can be
258 represented exactly as a binary64 number. In fact, most decimal numbers
259 with digits to the right of the decimal point lack an exact binary64
260 equivalent. For example, if you have a database column that is intended
261 to hold an item price in dollars and cents, the only cents value that
262 can be exactly represented are 0.00, 0.25, 0.50, and 0.75. Any other
263 numbers to the right of the decimal point result in an approximation.
264 If you provide a "price" value of 47.49, that number will be represented
265 in binary64 as:
266
267 </p><blockquote>
268 6683623321994527 &times; 2<sup><small>-47</small></sup>
269 </blockquote>
270
271 <p>Which works out to be:
272
273 </p><blockquote>
274 47.49000000000000198951966012828052043914794921875
275 </blockquote>
276
277 <p>That number is very close to 47.49, but it is not exact. It is a little
278 too big. If we reduce M by one to 6683623321994526 so that we have the
279 next smaller possible binary64 value, we get:
280
281 </p><blockquote>
282 47.4899999999999948840923025272786617279052734375
283 </blockquote>
284
285
286 <p>
287 This second number is too small.
288 The first number is closer to the desired value of 47.49, so that is the
289 one that gets used. But it is not exact. Most decimal values work this
290 way in IEEE 754. Remember the key point we made above:
291
292 </p><blockquote><b>
293 Floating point values are approximate.
294 </b></blockquote>
295
296 <p>If you remember nothing else about floating-point values,
297 please don't forget this one key idea.
298
299 </p><h3 id="is_it_close_enough_"><span>1.2.2. </span>Is it close enough?</h3>
300
301 <p>The precision provided by IEEE 754 Binary64 is sufficient for most computations.
302 For example, if "47.49" represents a price and inflation is running
303 at 2% per year, then the price is going up by about 0.0000000301 dollars per
304 second. The error in the recorded value of 47.49 represents about 66 nanoseconds
305 worth of inflation. So if the 47.49 price is exact
306 when you enter it, then the effects of inflation will cause the true value to
307 exactly equal the value actually stored
308 (47.4900000000000019895196601282805204391479492187) in less than
309 one ten-millionth of a second.
310 Surely that level of precision is sufficient for most purposes?
311
312 </p><h1 id="extensions_for_dealing_with_floating_point_numbers"><span>2. </span>Extensions For Dealing With Floating Point Numbers</h1>
313
314 <a name="ieee754ext"></a>
315
316 <h2 id="the_ieee754_c_extension"><span>2.1. </span>The ieee754.c Extension</h2>
317
318 <p>The ieee754 extension converts a floating point number between its
319 binary64 representation and the M&times;2<sup><small>E</small></sup> format.
320 In other words in the expression:
321
322 </p><blockquote>
323 <big>F = M &times 2<sup><small>E</small></sup></big>
324 </blockquote>
325
326 <p>The ieee754 extension converts between F and (M,E) and back again.
327
328 </p><p>The ieee754 extension is not part of the <a href="amalgamation.html">amalgamation</a>, but it is included
329 by default in the <a href="cli.html">CLI</a>. If you want to include the ieee754 extension in your
330 application, you will need to compile and load it separately.
331
332 <a name="ieee754"></a>
333
334 </p><h3 id="the_ieee754_function"><span>2.1.1. </span>The ieee754() function</h3>
335
336 <p>The ieee754(F) SQL function takes a single floating-point argument
337 as its input and returns a string that looks like this:
338
339 </p><blockquote>
340 'ieee754(M,E)'
341 </blockquote>
342
343 <p>Except that the M and E are replaced by the mantissa and exponent of the
344 floating point number. For example:
345
346 </p><div class="codeblock"><pre>sqlite> .mode box
347 sqlite> SELECT ieee754(47.49) AS x;
348 ┌───────────────────────────────┐
349 │ x │
350 ├───────────────────────────────┤
351 │ ieee754(6683623321994527,-47) │
352 └───────────────────────────────┘
353 </pre></div>
354
355 <p>
356 Going in the other direction, the 2-argument version of ieee754() takes
357 the M and E values and converts them into the corresponding F value:
358
359 </p><div class="codeblock"><pre>sqlite> select ieee754(6683623321994527,-47) as x;
360 ┌───────┐
361 │ x │
362 ├───────┤
363 │ 47.49 │
364 └───────┘
365 </pre></div>
366
367 <a name="ieee754m"></a>
368
369 <h3 id="the_ieee754_mantissa_and_ieee754_exponent_functions"><span>2.1.2. </span>The ieee754_mantissa() and ieee754_exponent() functions</h3>
370
371 <p>The text output of the one-argument form of ieee754() is great for human
372 readability, but it is awkward to use as part of a larger expression. Hence
373 the ieee754_mantissa() and ieee754_exponent() routines were added to return
374 the M and E values corresponding to their single argument F
375 value.
376 For example:
377
378 </p><div class="codeblock"><pre>sqlite> .mode box
379 sqlite> SELECT ieee754_mantissa(47.49) AS M, ieee754_exponent(47.49) AS E;
380 ┌──────────────────┬─────┐
381 │ M │ E │
382 ├──────────────────┼─────┤
383 │ 6683623321994527 │ -47 │
384 └──────────────────┴─────┘
385 </pre></div>
386
387 <a name="ieee754b"></a>
388
389 <h3 id="the_ieee754_from_blob_and_ieee754_to_blob_functions"><span>2.1.3. </span>The ieee754_from_blob() and ieee754_to_blob() functions</h3>
390
391 <p>The ieee754_to_blob(F) SQL function converts the floating point number F
392 into an 8-byte BLOB that is the big-endian binary64 encoding of that number.
393 The ieee754_from_blob(B) function goes the other way, converting an 8-byte
394 blob into the floating-point value that the binary64 encoding represents.
395
396 </p><p>So, for example, if you read
397 <a href="https://en.wikipedia.org/wiki/Double-precision_floating-point_format">on
398 Wikipedia</a> that the encoding for the minimum positive binary64 value is
399 0x0000000000000001, then you can find the corresponding floating point value
400 like this:
401
402 </p><div class="codeblock"><pre>sqlite> .mode box
403 sqlite> SELECT ieee754_from_blob(x'0000000000000001') AS F;
404 ┌───────────────────────┐
405 │ F │
406 ├───────────────────────┤
407 │ 4.94065645841247e-324 │
408 └───────────────────────┘
409 </pre></div>
410
411 <p>Or go the other way:
412
413 </p><div class="codeblock"><pre>sqlite> .mode box
414 sqlite> SELECT quote(ieee754_to_blob(4.94065645841247e-324)) AS binary64;
415 ┌─────────────────────┐
416 │ binary64 │
417 ├─────────────────────┤
418 │ X'0000000000000001' │
419 └─────────────────────┘
420 </pre></div>
421
422 <a name="decext"></a>
423
424 <h2 id="the_decimal_c_extension"><span>2.2. </span>The decimal.c Extension</h2>
425
426 <p>The decimal extension provides arbitrary-precision decimal arithmetic on
427 numbers stored as text strings. Because the numbers are stored to arbitrary
428 precision and as text, no approximations are needed. Computations can be
429 done exactly.
430
431 </p><p>The decimal extension is not (currently) part of the SQLite <a href="amalgamation.html">amalgamation</a>.
432 However, it is included in the <a href="cli.html">CLI</a>.
433
434 </p><p>There are three math functions available:
435
436 </p><p>
437 </p><ul>
438 <li> decimal_add(A,B)
439 </li><li> decimal_sub(A,B)
440 </li><li> decimal_mul(A,B)
441 </li><li> decimal_pow2(N)
442 </li></ul>
443
444
445 <p>The first three functions respectively add, subtract, and multiply their arguments
446 and return a new text string that is the decimal representation of the result. The
447 argument is interpreted as text.
448 There is no division operator because decimal division often does not generate
449 a finite decimal result.
450
451 </p><p>The decimal_pow2(N) function returns 2.0 raised to the N-th power where N is an
452 integer between -20000 and +20000.
453
454 </p><p>Use the decimal_cmp(A,B) to compare two decimal values. The result will
455 be negative, zero, or positive if A is less than, equal to, or greater than B,
456 respectively.
457
458 </p><p>The decimal_sum(X) function is an aggregate, like the built-in
459 <a href="lang_aggfunc.html#sumunc">sum() aggregate function</a>, except that decimal_sum() computes its result
460 to arbitrary precision and is therefore precise.
461
462 </p><p>The decimal extension provides the "decimal" collating sequences
463 that compares decimal text strings in numeric order.
464
465 </p><p>The decimal(X) and decimal_exp(X) generate a decimal representation for input X.
466 The decimal_exp(X) function returns the result in exponential notation (with a "e+NN"
467 at the end) and decimal(X) returns a pure decimal (without the "e+NN"). If the input
468 X is a floating point value, it is expanded to its exact decimal equivalent. For
469 example:
470
471 </p><div class="codeblock"><pre>sqlite> .mode qbox
472 sqlite> select decimal(47.49);
473 ┌──────────────────────────────────────────────────────┐
474 │ decimal(47.49) │
475 ├──────────────────────────────────────────────────────┤
476 │ '47.49000000000000198951966012828052043914794921875' │
477 └──────────────────────────────────────────────────────┘
478 </pre></div>
479 <p align="center"><small><i>This page last modified on <a href="https://sqlite.org/docsrc/honeypot" id="mtimelink" data-href="https://sqlite.org/docsrc/finfo/pages/floatingpoint.in?m=93c7688d94">2024-07-25 10:34:20</a> UTC </small></i></p>
480