2. Numerical Helpers
These help converting to and from floating point and real numbers in scheme.
2.1. Real to Float
Converts a real value (represented as an s9_cell
)
to an internal GFFLT
value.
The full function name is monolith_scheme_float_to_real
,
but can also be utilized via the macro definition
REAL2FLOAT
.
<<scheme_macros>>=
#define REAL2FLOAT monolith_scheme_real_to_float
<<scheme_function_declarations>>=
GFFLT monolith_scheme_real_to_float(s9_cell real);
Bignum architecture is still something of a dark art for me,
but from what I gathered reading the s9 source code and
some trial and error is that the architecture uses base 10
to store values. Converting the value is a matter of
extracting the mantissa and exponent components from the
cell, and then plugging those values into the pow
equation
seen below.
<<scheme_functions>>=
GFFLT monolith_scheme_real_to_float(s9_cell real)
{
GFFLT val;
int mant;
int expt;
if (s9_integer_p(real)) {
return integer_value(NULL, real);
}
mant = s9_bignum_to_int(s9_real_mantissa(real));
expt = s9_real_exponent(real);
val = mant * pow(10, expt);
return val;
}
2.2. Float to Real
Converts a floating point value to a real value. The decimal precision needs to be explicitly specified.
<<scheme_macros>>=
#define FLOAT2REAL monolith_scheme_float_to_real
<<scheme_function_declarations>>=
s9_cell monolith_scheme_float_to_real(GFFLT val, int p);
<<scheme_functions>>=
s9_cell monolith_scheme_float_to_real(GFFLT val, int p)
{
GFFLT c;
unsigned int ival;
int sign;
c = pow(10, p);
sign = val < 0 ? -1 : 1;
val = fabs(val);
ival = floor(val);
val = floor(c * (ival + (val - ival)));
return s9_make_real(sign, -p, s9_make_integer(val));
}
prev | home | next