division: added integer division (because i can't figure out how to do it better

This commit is contained in:
2017-07-31 15:55:01 -04:00
parent 6bcacabc3b
commit 6f93ebcb24
4 changed files with 33 additions and 0 deletions

View File

@@ -22,6 +22,7 @@ double silly_to_double(silly); // convert a silly number into a double
silly silly_add(silly, silly); // addition
silly silly_sub(silly, silly); // subtraction
silly silly_mul(silly, silly); // multiplication
silly silly_div(silly, silly); // division (integer precision only :( )
char* silly_to_string(silly); // converts a fixed point value to a string (memory is now yours)
```

12
silly.c
View File

@@ -77,6 +77,18 @@ silly silly_mul(silly x, silly y) {
return z;
}
silly silly_div(silly x, silly y) {
silly z;
z.sign = x.sign ^ y.sign;
uint64_t x0 = (((uint64_t) x.before) << 32) + x.after;
uint64_t y0 = (((uint64_t) y.before) << 32) + y.after;
z.before = x0 / y0;
z.after = 0;
return z;
}
char* silly_to_string(silly s) {
char* res = malloc(23);

View File

@@ -15,6 +15,7 @@ silly make_silly(short, int, int);
silly silly_add(silly, silly);
silly silly_sub(silly, silly);
silly silly_mul(silly, silly);
silly silly_div(silly, silly);
silly silly_from_float(float);
silly silly_from_double(double);

View File

@@ -116,12 +116,31 @@ TEST silly_conversion() {
PASS();
}
TEST silly_division() {
silly x = make_silly(0, 10, 0);
silly y = make_silly(1, 5, 0);
ASSERT_EQ_FMT(-2.0, silly_to_double(silly_div(x, y)), "%f");
y = make_silly(1, 2, 5);
ASSERT_EQ_FMT(-4.0, silly_to_double(silly_div(x, y)), "%f");
// :(
y = make_silly(1, 2, 3);
ASSERT_EQ_FMT(-4.0, silly_to_double(silly_div(x, y)), "%f");
PASS();
}
SUITE(tests) {
RUN_TEST(silly_zeros_is_zero);
RUN_TEST(silly_string);
RUN_TEST(silly_addition);
RUN_TEST(silly_subtraction);
RUN_TEST(silly_multiplication);
RUN_TEST(silly_division);
RUN_TEST(silly_conversion);
}