Skip to content
Tutorials Center
My learning

Topics

Lesson 3 of 38 ยท Getting Started

Constants, Units and Conventions

Use scipy.constants for physical constants and unit conversions, and learn SciPy's array conventions, result objects like OptimizeResult and how to read the docs.

Before the algorithms, two small things make everything else easier: a library of trusted constants and unit factors, and a clear picture of how SciPy functions take input and return results. scipy.constants saves you from typing 299792458 from memory or guessing how many meters are in a mile. The conventions section explains why SciPy functions feel alike, so a new function is easy to pick up.

Physical constants and unit factors

scipy.constants holds the CODATA values of fundamental constants as plain floats, in SI units: meters, kilograms, seconds, joules. It also holds prefixes (kilo, milli) and conversion factors that turn a unit into SI. The rule for factors is simple: multiply to convert to SI.

Python Constants and conversion factors

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Three access styles appear above:

  • Module attributes such as C.c and C.h for the best-known constants.
  • The physical_constants dictionary, keyed by the official name. Each entry is a tuple (value, unit, uncertainty). It contains hundreds of constants, and C.find("mass") searches the names.
  • Conversion functions where a pure factor is not enough. Temperatures need an offset as well as a scale, so convert_temperature exists.

Constants are updated when the scientific community revises them, so the last digits of values such as the electron mass can change between SciPy releases. Exactly defined values like c and h do not.

Using constants in a calculation

Because the factors are SI multipliers, a unit-aware calculation reads naturally: multiply the number by its unit factor on the way in, divide by the factor of the unit you want on the way out.

Python Photon energy and unit arithmetic

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

A 500 nm photon carries about 2.48 eV. Keeping every quantity in SI inside your code and converting only at the edges (reading input and printing output) prevents the unit mix-ups that have ruined real spacecraft missions.

Warning: scipy.constants does not track units. It cannot tell you that you added meters to seconds. For automatic unit checking, use a units package such as pint.

Searching the table: find, value, unit and precision

The physical_constants dictionary has several hundred entries with long official names such as "neutron mass" or "Rydberg constant times hc in eV", and nobody remembers them all. Three helpers make the table searchable:

  • constants.find("keyword") returns a sorted list of all names that contain the keyword (case-insensitive). Without a keyword it returns every name. Use disp=True to print the matches instead of returning them.
  • constants.value(name), constants.unit(name) and constants.precision(name) return one field of an entry: the value, its unit as a string, and the relative uncertainty (uncertainty divided by value).

The unit factors come in families, and every one converts to SI by multiplying:

Family Examples (all in SI after multiplying)
length inch, foot, yard, mile, nautical_mile, light_year, parsec, angstrom
mass gram, pound, ounce, metric_ton, atomic_mass
time minute, hour, day, week, year
pressure atm, bar, torr, mmHg, psi (result in pascal)
energy and power eV, calorie, Btu, hp (result in joule or watt)
speed and volume kmh, mph, knot, liter, gallon, fluid_ounce
angle degree, arcmin, arcsec (result in radians)
Python Find constants and convert pressure units

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

A tire at 32 psi is about 2.2 bar. Dividing by the target unit's factor is the same recipe as always: multiply on the way in, divide on the way out. The precision of the proton mass is a few parts in a billion, a reminder that even the best-known constants are measured quantities with an error bar (only values defined exactly by the SI, such as c and h, have an uncertainty of zero).

Array in, array out

Most SciPy functions follow the same shape contract, which is why they feel alike:

  • They accept Python numbers, lists or NumPy arrays and convert them with np.asarray.
  • Element-wise functions (stats.norm.cdf, special.expit) return the same shape you gave them: a scalar in, a scalar out; an array in, an array out.
  • Reducing functions return a number or a small object.
  • Integer input is generally promoted to floating point.
Python Scalars, lists and arrays

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The same function handled a scalar, a list and a 2-D array. Learn this pattern once, and you can pass whole arrays to almost anything instead of looping.

flowchart LR
    I["Input<br/>number, list or ndarray"] --> F["SciPy function"]
    F --> O["Output<br/>same shape or result object"]
    F --> W["Warnings<br/>and status flags"]

Inputs are converted to arrays; outputs keep the shape, or come back as a result object that also carries diagnostics.

Result objects

Algorithms that do more than compute one number return a result object: a bundle of named fields. You have already met OptimizeResult from minimize and OdeResult from solve_ivp. Statistics functions return named tuples such as LinregressResult. These objects support attribute access (res.x), and many support dictionary access (res["x"]) and tuple unpacking too.

Python Reading result objects

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The most important habit: check the status field before trusting the value. For optimizers that is res.success and res.message; for ODE solvers sol.success; for fitting routines the covariance matrix. A result can contain numbers even though the algorithm gave up.

Reading the documentation and avoiding version traps

Every function's docs follow one layout: a signature, Parameters, Returns, Notes (the math and its limits) and Examples. Read Returns first, to know whether you get an array or an object, and the Notes for the algorithm's assumptions. In a notebook or the Python prompt, help(optimize.minimize) prints the same text offline.

A few traps you will meet in older tutorials:

  • interp1d is legacy; new code uses make_interp_spline, CubicSpline and friends (covered in the interpolation lessons).
  • scipy.sparse has two APIs: the older *_matrix classes and the newer *_array classes. They differ in what * does. This tutorial uses arrays.
  • Deprecated and removed names change across releases. If a tutorial's import fails, check the current docs for the replacement rather than pinning an old version.
  • Pyodide versions lag behind the newest SciPy a little, so examples here only use features available in the version this site runs.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What rule does scipy.constants use for unit conversion factors such as C.mile?

    Each factor is the size of the unit expressed in SI units, so 1 mile is 1609.344 meters, and multiplying a number of miles by C.mile gives meters.
  2. 2. What does scipy.constants.physical_constants["electron mass"] return?

    The dictionary stores (value, unit, uncertainty) tuples, which is why the example unpacks three names.
  3. 3. stats.norm.cdf([-1, 0, 1]) returns what?

    Element-wise SciPy functions accept array-like input and return an array of the same shape.
  4. 4. An optimizer returns an OptimizeResult with an x value. What should you check before using x?

    Algorithms can stop without converging and still report a point. The status fields tell you whether to trust it.

Summary

  • scipy.constants provides SI-valued constants, prefixes and conversion factors; multiply by a factor to convert to SI.
  • physical_constants maps names to (value, unit, uncertainty); find, value, unit and precision search and read it, and convert_temperature handles offsets.
  • SciPy functions accept scalars, lists and arrays and return the matching shape.
  • Result objects such as OptimizeResult bundle values with diagnostics; check success before trusting them.
  • Read Returns and Notes in the docs, and watch for legacy APIs such as interp1d and sparse matrices versus arrays.

Next: Reading and Writing Data Files.