1
2
3
4
5
6 """This provides useful general math tools (OBSOLETE).
7
8 This module and its C code equivalent are considered to be obsolete, and
9 are likely to be deprecated in a future release of Biopython, before being
10 removed. Please get in touch via the mailing list if this will affect you.
11
12 Functions:
13 fcmp Compare two floating point numbers, up to a specified precision.
14 intd Represent a floating point number as an integer.
15 safe_log log, but returns an arbitrarily small number for log(0).
16 safe_exp exp, but returns a large or small number instead of overflows.
17
18 """
19 import math
20
21 -def fcmp(x, y, precision):
22 """fcmp(x, y, precision) -> -1, 0, or 1"""
23 if math.fabs(x-y) < precision:
24 return 0
25 elif x < y:
26 return -1
27 return 1
28
29 -def intd(x, digits_after_decimal=0):
30 """intd(x[, digits_after_decimal]) -> int x, rounded
31
32 Represent a floating point number with some digits after the
33 decimal point as an integer. This is useful when floating point
34 comparisons are failing due to precision problems. e.g.
35 intd(5.35, 1) -> 54.
36
37 """
38 precision = 10.**digits_after_decimal
39 if x >= 0:
40 x = int(x * precision + 0.5)
41 else:
42 x = int(x * precision - 0.5)
43 return x
44
46 """safe_log(n, zero=None, neg=None) -> log(n)
47
48 Calculate the log of n. If n is 0, returns the value of zero. If n is
49 negative, returns the value of neg.
50
51 """
52 if n < 0:
53 return neg
54 elif n < 1E-100:
55 return zero
56 return math.log(n)
57
58 LOG2 = math.log(2)
60 """safe_log2(n, zero=None, neg=None) -> log(n)
61
62 Calculate the log base 2 of n. If n is 0, returns the value of
63 zero. If n is negative, returns the value of neg.
64
65 """
66 l = safe_log(n, zero=zero, neg=neg)
67 if l is None:
68 return l
69 return l/LOG2
70
72 """safe_exp(n, under=None, over=None) -> e**n
73
74 Guaranteed not to overflow. Instead of overflowing, it returns
75 the values of 'under' for underflows or 'over' for overflows.
76
77 """
78 try:
79 return math.exp(n)
80 except OverflowError:
81 if n < 0:
82 return under
83 return over
84 raise "How did I get here?"
85
86
87
88 try:
89 from cmathfns import *
90 except ImportError:
91 pass
92