Last active
August 29, 2015 14:16
-
-
Save MitMaro/a30eb6896464a03092d7 to your computer and use it in GitHub Desktop.
How to combine two reals into one in javascript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // some number that when 360 * precision * 100 + 50 * precision won't overflow an integer | |
| // number of positions after the decimal to keep | |
| var digits = 4; | |
| var precision = Math.pow(10, digits); | |
| function combine(x, y, maxydigits) { | |
| x = Math.floor(x * precision); | |
| y = Math.floor(y * precision); | |
| var maxy = Math.pow(10, maxydigits) * precision; | |
| return x * maxy + y; | |
| } | |
| function extract(z, maxydigits) { | |
| var maxy = Math.pow(10, maxydigits) * precision; | |
| var x = Math.floor(z / maxy); | |
| return { | |
| x: x / precision, | |
| y: z % maxy / precision | |
| } | |
| } | |
| // test | |
| for (var i = 0; i <= 360; i += 0.5) { | |
| for (var j = 0; j <= 50; j += 0.5) { | |
| var z = combine(i, j, 3); | |
| var e = extract(z, 3) | |
| if (Math.floor(i * precision) !== Math.floor(e.x * precision) || Math.floor(j * precision) !== Math.floor(e.y * precision)) { | |
| console.log('Failed on ' + i + ', ' + j + ': ' + z, ' # ' + e.x + ', ' + e.y); | |
| return; | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment