1 /* Copyright 2000 by Jeffrey Chang. All rights reserved.
2 * This code is part of the Biopython distribution and governed by its
3 * license. Please see the LICENSE file that should have been included
4 * as part of this package.
17 /************************************** Exported Functions ***********/
19 static char cmathfns_intd__doc__[] =
20 "intd(x[, digits_after_decimal]) -> int x, rounded\n\
22 Represent a floating point number with some digits after the\n\
23 decimal point as an integer. This is useful when floating point\n\
24 comparisons are failing due to precision problems. e.g.\n\
25 intd(5.35, 1) -> 54.\n\
29 static PyObject *cmathfns_intd(
30 PyObject *self, PyObject *args, PyObject *keywds)
32 PyObject *digits_after_decimal = Py_None;
36 static char *kwlist[] = {"x", "digits_after_decimal", NULL};
37 if(!PyArg_ParseTupleAndKeywords(args, keywds, "d|O", kwlist,
38 &x, &digits_after_decimal))
41 if(digits_after_decimal == Py_None)
44 digits = PyNumber_AsDouble(digits_after_decimal);
45 if(PyErr_Occurred()) {
49 precision = pow(10, digits);
51 x = (int)(x * precision + 0.5);
53 x = (int)(x * precision - 0.5);
54 return PyFloat_FromDouble(x);
60 static char cmathfns_fcmp__doc__[] =
61 "fcmp(x, y, precision) -> -1, 0, or 1";
63 static PyObject *cmathfns_fcmp(
64 PyObject *self, PyObject *args, PyObject *keywds)
66 double x, y, precision;
69 static char *kwlist[] = {"x", "y", "precision", NULL};
70 if(!PyArg_ParseTupleAndKeywords(args, keywds, "ddd", kwlist,
74 if(fabs(x-y) < precision)
79 return PyInt_FromLong(result);
84 static char cmathfns_safe_log__doc__[] =
85 "safe_log(n, zero=None, neg=None) -> log(n)\n\
87 Calculate the log of n. If n is 0, returns the value of zero. If n is\n\
88 negative, returns the value of neg.\n\
92 static PyObject *cmathfns_safe_log(
93 PyObject *self, PyObject *args, PyObject *keywds)
95 PyObject *zero = Py_None,
99 static char *kwlist[] = {"n", "zero", "neg", NULL};
101 if(!PyArg_ParseTupleAndKeywords(args, keywds, "d|OO", kwlist,
108 } else if(n < 1E-100) {
113 return PyFloat_FromDouble(log(n));
119 /************************************** Module definition stuff ******/
121 static PyMethodDef cmathfnsMethods[] = {
122 {"fcmp", (PyCFunction)cmathfns_fcmp, METH_VARARGS|METH_KEYWORDS,
123 cmathfns_fcmp__doc__},
124 {"intd", (PyCFunction)cmathfns_intd, METH_VARARGS|METH_KEYWORDS,
125 cmathfns_intd__doc__},
126 {"safe_log", (PyCFunction)cmathfns_safe_log, METH_VARARGS|METH_KEYWORDS,
127 cmathfns_safe_log__doc__},
131 static char cmathfns__doc__[] =
132 "This provides helper functions for the mathfns module.\n\
133 You should never import this module on its own.\n\
137 void initcmathfns(void)
139 (void) Py_InitModule3("cmathfns", cmathfnsMethods, cmathfns__doc__);