Created
July 1, 2022 20:35
-
-
Save MilesCranmer/142b6c3a4599aa428582301a6fc75eeb to your computer and use it in GitHub Desktop.
Reduce precision of constants in a string
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import re | |
def reduce_precision_of_constants_in_string(s, precision=3): | |
# Find all constants in the string: | |
constants = re.findall(r"\b[-+]?\d*\.\d+|\b[-+]?\d+\.?\d*", s) | |
for c in constants: | |
reduced_c = "{:.{precision}g}".format(float(c), precision=precision) | |
s = s.replace(c, reduced_c) | |
return s | |
s = "1.093840293 * exp(x1 * 0.00031823)" | |
print(reduce_precision_of_constants_in_string(s)) | |
# >> '1.09 * exp(x1 * 0.000318)'" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment