- [C/C++/Python/PHP/JS/...] Code Fragments and Routines
- 26 Dec 2013 07:27:22 pm
- Last edited by KermMartian on 02 Mar 2015 09:24:41 pm; edited 2 times in total
We have a TI-BASIC Code Fragments and Routines, a z80 Assembly Routines thread, and even a Useful Prizm Routines thread. However, I can't find such a thread for computer, mobile, and web programming in C, C++, Python, PHP, Javascript, Java, and similar languages, so here it is. I'll start with a routine I just wrote.
[Python/PHP/Computer] Floating-Point Number to Base-10 Mantissa, Exponent, and Sign
In C, C++, and other low-level languages, you can directly extract the sign, exponent, and mantissa of a number in base-2 from its representation in the computer's memory or CPU registers. However, base-10 is more difficult, and higher-level languages don't have a way to access base-anything. Here's code in Python (the algorithm for which would work in other languages) that computes the sign, exponent, and mantissa from a floating-point number.
Code:
Here it is in Python:
Code:
Here it is in PHP:
Code:
[Python/PHP/Computer] Floating-Point Number to Base-10 Mantissa, Exponent, and Sign
In C, C++, and other low-level languages, you can directly extract the sign, exponent, and mantissa of a number in base-2 from its representation in the computer's memory or CPU registers. However, base-10 is more difficult, and higher-level languages don't have a way to access base-anything. Here's code in Python (the algorithm for which would work in other languages) that computes the sign, exponent, and mantissa from a floating-point number.
Code:
r00t@amethyst:# python test.py
-1.23457e+09 =?= -1.000000 * 1.234568 * 10 ^ 9
-1.23457 =?= -1.000000 * 1.234568 * 10 ^ 0
-1.23e-11 =?= -1.000000 * 1.230000 * 10 ^ -11
1.2345 =?= 1.000000 * 1.234500 * 10 ^ 0
124.236 =?= 1.000000 * 1.242356 * 10 ^ 2
2.64768e+13 =?= 1.000000 * 2.647683 * 10 ^ 13
Code:
#!/usr/bin/python
import math
tests = [ -1234567890, -1.2345678, -0.0000000000123, 1.2345, 124.23562472, 26476832623454.453 ];
def mantexp(val):
val = float(val)
sign = -1 if val < 0 else 1
val = abs(val)
exp = 0 if val == 0 else int(math.floor(math.log10(val)))
mant = val / ( 10 ** exp )
return [sign, mant, exp]
for test in tests:
sign, mant, exp = mantexp(test)
print "%g =?= %f * %f * 10 ^ %d" % (test, sign, mant, exp)
Code:
<?php
$tests = Array(-1234567890, -1.2345678, -0.0000000000123, 1.2345, 124.23562472, 26476832623454.453);
function mantexp($val) {
$sign = ($val < 0)?-1:1;
$val = abs($val);
$expn = ($val == 0)?0:floor(log10($val));
$mant = $val / pow(10,$expn);
return Array($sign, $mant, $expn);
}
foreach($tests as $test) {
list($sign, $mant, $expn) = mantexp($test);
printf("%g =?= %f * %f * 10 ^ %d\n", $test, $sign, $mant, $expn);
}
?>