Skip to content

Commit 5a936f5

Browse files
committed
create utils.round_sig() for rounding number to n sig figures
1 parent 9f7abf3 commit 5a936f5

File tree

2 files changed

+20
-0
lines changed

2 files changed

+20
-0
lines changed

src/python/pipelines_utils/utils.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717

1818
from __future__ import print_function
1919
import sys, gzip, json, uuid
20+
from math import log10, floor
2021
from rdkit import Chem
2122
from rdkit.Chem import AllChem
2223
from rdkit_utils.sanifix import fix_mol
@@ -31,6 +32,10 @@ def log(*args, **kwargs):
3132
"""
3233
print(*args, file=sys.stderr, **kwargs)
3334

35+
def round_sig(x, sig):
36+
"""Round the number to the specified number of significant figures"""
37+
return round(x, sig-int(floor(log10(abs(x))))-1)
38+
3439
def add_default_input_args(parser):
3540
parser.add_argument('-i', '--input', help="Input file, if not defined the STDIN is used")
3641
parser.add_argument('-if', '--informat', choices=['sdf', 'json'], help="Input format. When using STDIN this must be specified.")
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
import unittest
2+
3+
from pipelines_utils import utils
4+
5+
6+
class UtilsTestCase(unittest.TestCase):
7+
8+
9+
def test_round_sig(self):
10+
"""Rounding of significant figures
11+
"""
12+
self.assertEquals(utils.round_sig(1.23456789, 2), 1.2)
13+
self.assertEquals(utils.round_sig(1.23456789, 3), 1.23)
14+
self.assertEquals(utils.round_sig(1.23456789, 6), 1.23457)
15+

0 commit comments

Comments
 (0)