Created
April 5, 2017 00:54
-
-
Save jbryanscott/d06ad3555b9664b23dcddc3a84ba6761 to your computer and use it in GitHub Desktop.
Displaying proper significant figures in Python
This file contains 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
from math import floor, log10 | |
def display_sigfig(x, sigfigs=2) -> str: | |
''' | |
Suppose we want to show 2 significant figures. Implicitly we want to show 3 bits of information: | |
- The order of magnitude | |
- Significant digit #1 | |
- Significant digit #2 | |
''' | |
if sigfigs < 1: | |
raise Exception('Cannot have fewer than 1 significant figures. ({} given)'.format(sigfigs)) | |
order_of_magnitude = floor(log10(abs(x))) | |
# Because we get one sigfig for free, to the left of the decimal | |
decimals = (sigfigs - 1) | |
x /= pow(10, order_of_magnitude) | |
x = round(x, decimals) | |
x *= pow(10, order_of_magnitude) | |
# Subtract from decimals the sigfigs we get from the order of magnitude | |
decimals -= order_of_magnitude | |
# But we can't have a negative number of decimals | |
decimals = max(0, decimals) | |
return '{:,.{dec}f}'.format(x, dec=decimals) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment