Created
March 16, 2022 23:29
-
-
Save EllipticEllipsis/d42c9798992f38fbdf932aa2a0261841 to your computer and use it in GitHub Desktop.
Program to attempt to figure out the multiplication by a power of 10 that gives a particular float.
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
| #include <stdint.h> | |
| #include <stdio.h> | |
| #define ARRAY_COUNT(arr) (sizeof(arr) / sizeof(arr[0])) | |
| // Test values for 0.05f | |
| // float test_mult[] = { | |
| // 5.0e-06f * 10000.0f, 5.0e-05f * 1000.0f, 0.0005f * 100.0f, 0.005f * 10.0f, 0.05f * 1.0f, | |
| // 0.5f * 0.1f, 5.0f * 0.01f, 50.0f * 0.001f, 500.0f * 0.0001f, | |
| // }; | |
| // float test_div[] = { | |
| // 5.0e-06f / 0.0001f, 5.0e-05f / 0.001f, 0.0005f / 0.01f, | |
| // 0.005f / 0.1f, 0.05f / 1.0f, 0.5f / 10.0f, | |
| // 5.0f / 100.0f, 50.0f / 1000.0f, 500.0f / 10000.0f, | |
| // }; | |
| typedef union { | |
| float f; | |
| uint32_t x; | |
| } HexFloat; | |
| uint32_t hex_of_float(float f) { | |
| HexFloat xf; | |
| xf.f = f; | |
| return xf.x; | |
| } | |
| double multipliers_double[] = { 10000.0, 1000.0, 100.0, 10.0, 1.0, 0.1, 0.01, 0.001, 0.0001 }; | |
| double divisors_double[] = { 0.0001, 0.001, 0.01, 0.1, 1.0, 10.0, 100.0, 1000.0, 10000.0 }; | |
| float multipliers[] = { 10000.0f, 1000.0f, 100.0f, 10.0f, 1.0f, 0.1f, 0.01f, 0.001f, 0.0001f }; | |
| float divisors[] = { 0.0001f, 0.001f, 0.01f, 0.1f, 1.0f, 10.0f, 100.0f, 1000.0f, 10000.0f }; | |
| int main(int argc, char** argv) { | |
| double input; | |
| size_t i; | |
| if (argc < 2) { | |
| fprintf(stderr, "Not enough inputs: need float"); | |
| return 1; | |
| } | |
| if (sscanf(argv[1], "%lf", &input) == 0) { | |
| fprintf(stderr, "Could not read float from argument %s", argv[1]); | |
| return 1; | |
| } | |
| for (i = 0; i < ARRAY_COUNT(multipliers); i++) { | |
| float temp = input * divisors_double[i]; | |
| float output = temp * multipliers[i]; | |
| printf("%10g * %-10g = %.10f, %08X ", temp, multipliers[i], output, hex_of_float(output)); | |
| // printf("%08X", hex_of_float(test_mult[i])); | |
| putchar('\n'); | |
| } | |
| putchar('\n'); | |
| for (i = 0; i < ARRAY_COUNT(multipliers); i++) { | |
| float temp = input / multipliers_double[i]; | |
| float output = temp / divisors[i]; | |
| printf("%10g / %-10g = %.10f, %08X ", temp, divisors[i], output, hex_of_float(output)); | |
| // printf("%08X", hex_of_float(test_div[i])); | |
| putchar('\n'); | |
| } | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment