1 | ''' |
---|
2 | *GSASIIpy3: Python 3.x Routines* |
---|
3 | ================================ |
---|
4 | |
---|
5 | Module to hold python 3-compatible code, to keep it separate from |
---|
6 | code that will break with __future__ options. |
---|
7 | |
---|
8 | ''' |
---|
9 | from __future__ import division |
---|
10 | import numpy as np |
---|
11 | # de |
---|
12 | sind = sin = s = lambda x: np.sin(x*np.pi/180.) |
---|
13 | cosd = cos = c = lambda x: np.cos(x*np.pi/180.) |
---|
14 | tand = tan = t = lambda x: np.tan(x*np.pi/180.) |
---|
15 | sqrt = sq = lambda x: np.sqrt(x) |
---|
16 | pi = np.pi |
---|
17 | |
---|
18 | def FormulaEval(string): |
---|
19 | '''Evaluates a algebraic formula into a float, if possible. Works |
---|
20 | properly on fractions e.g. 2/3 only with python 3.0+ division. |
---|
21 | |
---|
22 | Expressions such as 2/3, 3*pi, sin(45)/2, 2*sqrt(2), 2**10 can all |
---|
23 | be evaluated. |
---|
24 | |
---|
25 | :param str string: Character string c |
---|
26 | ''' |
---|
27 | try: |
---|
28 | val = float(eval(string)) |
---|
29 | if np.isnan(val) or np.isinf(val): return None |
---|
30 | except: |
---|
31 | return None |
---|
32 | return val |
---|
33 | |
---|
34 | def FormatValue(val,maxdigits=10): |
---|
35 | '''Format a float to fit in maxdigits spaces, showing as much |
---|
36 | precision as possible, more or less |
---|
37 | ''' |
---|
38 | # does the standard str() conversion fit? |
---|
39 | string = str(val) |
---|
40 | if len(string) <= maxdigits: return string.strip() |
---|
41 | # negative numbers, leave room for a sign |
---|
42 | if val < 0: maxdigits -= 1 |
---|
43 | decimals = maxdigits - 2 |
---|
44 | if abs(val) < 1e-99 or abs(val) > 1e99: |
---|
45 | decimals = maxdigits - 6 |
---|
46 | fmt = "{" + (":{:d}.{:d}g".format(maxdigits,decimals))+"}" # create format string |
---|
47 | elif abs(val) < 1e-9 or abs(val) > 1e9: |
---|
48 | decimals = maxdigits - 5 |
---|
49 | fmt = "{" + (":{:d}.{:d}g".format(maxdigits,decimals))+"}" |
---|
50 | elif abs(val) < 10**(4-decimals): # make sure at least 4 decimals show |
---|
51 | decimals = maxdigits - 5 |
---|
52 | fmt = "{" + (":{:d}.{:d}g".format(maxdigits,decimals))+"}" |
---|
53 | elif abs(val) >= 10**decimals: # deal with large numbers in smaller spaces |
---|
54 | decimals = maxdigits - 5 |
---|
55 | fmt = "{" + (":{:d}.{:d}g".format(maxdigits,decimals))+"}" |
---|
56 | elif abs(val) < 1: # use f format for small numbers |
---|
57 | decimals = maxdigits - 2 |
---|
58 | fmt = "{" + (":{:d}.{:d}f".format(maxdigits,decimals))+"}" |
---|
59 | else: # in range where g formatting should do what I want |
---|
60 | decimals = maxdigits - 1 |
---|
61 | fmt = "{" + (":{:d}.{:d}g".format(maxdigits,decimals))+"}" |
---|
62 | return fmt.format(val).strip() |
---|