|
8 | 8 | """ |
9 | 9 | import os |
10 | 10 | import fnmatch |
| 11 | +from math import trunc, modf |
11 | 12 | import numpy as np |
12 | 13 | from scipy import interpolate |
13 | 14 | from scipy.special import exp1 |
@@ -864,6 +865,71 @@ def scale_classical(inDict, ip): |
864 | 865 | print(' input dict does not have the correct keys') |
865 | 866 | return |
866 | 867 |
|
| 868 | +def sig_fig(x, sig, verbose=False): |
| 869 | + """ |
| 870 | +
|
| 871 | + :param x: a floating point number |
| 872 | + :type x: float |
| 873 | +
|
| 874 | + :param sig: the number of desired significant figures |
| 875 | + :type sig: int |
| 876 | +
|
| 877 | + returns a string of lenght 15 of the number x converted to the number |
| 878 | + of significant figures |
| 879 | +
|
| 880 | + round_sig provided by: |
| 881 | + https://stackoverflow.com/users/331701/evgeny |
| 882 | + """ |
| 883 | + |
| 884 | + from math import log10, floor |
| 885 | + def round_sig(x, sig=2): |
| 886 | + return round(x, sig-int(floor(log10(abs(x))))-1) |
| 887 | + |
| 888 | + fpart, ipart = modf(x) |
| 889 | + ipart_str = '%i'%(ipart) |
| 890 | + |
| 891 | + if x >= 0.: |
| 892 | + fpart_str = str(fpart) |
| 893 | + if verbose: |
| 894 | + print('len ipart: %i sig: %i'%(len(ipart_str), sig)) |
| 895 | + if len(ipart_str) >= sig: |
| 896 | + ipart_20s = '%15.0f'%(round_sig(ipart, sig)) |
| 897 | + fsig = sig - len(ipart_str) |
| 898 | + if verbose: |
| 899 | + print('fsig: %i'%(fsig)) |
| 900 | + return ipart_20s + fpart_str[1:fsig + 2] |
| 901 | + else: |
| 902 | + x_trunc = "%i"%(trunc(x)) |
| 903 | + d1 = 15 |
| 904 | + d2 = sig - len(x_trunc) |
| 905 | + if d2 < 1: |
| 906 | + d2 = 0 |
| 907 | + dd = '%i.%if'%(d1, d2) |
| 908 | + dd = '%' + dd |
| 909 | + return dd%(x) |
| 910 | + elif x < 0.: |
| 911 | + if verbose: |
| 912 | + print('len ipart: %i sig: %i'%(len(ipart_str), sig)) |
| 913 | + if len(ipart_str) > sig: |
| 914 | + fpart_str = str(abs(fpart)) |
| 915 | + ipart_20s = '%15s'%(round_sig(ipart, sig)) |
| 916 | + fsig = sig - len(ipart_str) |
| 917 | + if verbose: |
| 918 | + print('fsig: %i'%(fsig)) |
| 919 | + return ipart_20s |
| 920 | + else: |
| 921 | + x_trunc = "%i"%(trunc(x)) |
| 922 | + d1 = 15 |
| 923 | + d2 = sig - len(x_trunc) + 1 |
| 924 | + if d2 < 1: |
| 925 | + d2 = 0 |
| 926 | + if verbose: |
| 927 | + print('d1: %i d2: %i'%(d1, d2)) |
| 928 | + dd = '%i.%if'%(d1, d2) |
| 929 | + dd = '%' + dd |
| 930 | + return dd%(x) |
| 931 | + |
| 932 | + |
867 | 933 | def units(defaults): |
868 | 934 | """ to create a set of units compatible with ChiantiPy default values |
869 | 935 | """ |
|
0 commit comments