SciPy Constants
The constants module gives you scientific values and unit conversions, so you never have to type them by hand.
Why Use Constants?
Typing 3.14 or 9.8 yourself is easy, but it can introduce small errors. scipy.constants stores exact, internationally agreed values.
Maths and Physics Constants
Example
from scipy import constants
print(constants.pi)
print(constants.golden)
print(constants.speed_of_light)
print(constants.g)3.141592653589793 1.618033988749895 299792458.0 9.80665
| Name | Meaning | Unit |
|---|---|---|
pi | Ratio of a circle's circumference to its diameter | none |
golden | The golden ratio | none |
speed_of_light (or c) | Speed of light in vacuum | metres per second |
g | Standard gravity on Earth | metres per second squared |
Avogadro | Particles in one mole | per mole |
Seeing All Constants
Example
from scipy import constants
names = [n for n in dir(constants) if not n.startswith("_")]
print(len(names) > 100)True
There are well over a hundred names in the module.
Unit Conversion
The units are stored as their value in the SI base unit: metres for length, kilograms for mass, seconds for time. To convert to SI, multiply. To convert from SI, divide.
Example
from scipy import constants
print(constants.kilo) # 1000
print(constants.minute) # seconds in a minute
print(constants.hour) # seconds in an hour
print(constants.inch) # metres in an inch
print(constants.mile) # metres in a mile1000.0 60.0 3600.0 0.0254 1609.3439999999998
The last value has a tiny rounding detail at the end. This is normal for decimal numbers on computers.
A Practical Conversion
A cricket pitch is 22 yards long. How many metres is that? And how many minutes are in 2.5 hours?
Example
from scipy import constants
pitch_m = 22 * constants.yard
print(round(pitch_m, 2))
minutes = 2.5 * constants.hour / constants.minute
print(minutes)20.12 150.0
Mass and Weight
Example
from scipy import constants
flour_lb = 10
flour_kg = flour_lb * constants.pound
print(round(flour_kg, 2))4.54
Temperature
Temperature is different because the scales do not start at zero together. Use convert_temperature():
Example
from scipy.constants import convert_temperature
print(convert_temperature(40, "Celsius", "Fahrenheit"))
print(convert_temperature(98.6, "Fahrenheit", "Celsius"))
print(convert_temperature(0, "Celsius", "Kelvin"))104.0 37.0 273.15
Karachi's 40 degree summer day is 104 degrees Fahrenheit.
You can shorten the scale names: "C", "F" and "K" also work.
Exercise
Exercise
How do you convert 5 inches to metres with scipy.constants?
