Please enable JavaScript to use CodeHS

Coding for High School Math

Coding for Exponents and Logarithms

Exponents describe fast growth and decay. Logarithms answer the question: "How long will it take?" Code can model populations, investments, radioactive decay, and solve for time in seconds.

High School Math ~12 min Algebra 2 / Precalculus
Interest

Compound interest

If you invest P dollars at an annual rate r, compounded n times per year for t years, the amount is:

A = P(1 + r/n)^(nt)

The more often interest is compounded, the faster the balance grows. In the limit, as n → ∞, the formula becomes A = Pe^(rt), which uses Euler's number e ≈ 2.718.

Growth

Exponential growth and decay

The same idea applies to populations, bacteria, and radioactive substances. Continuous growth uses the natural base e:

A = P · e^(rt)

When r is positive, the quantity grows. When r is negative, it decays. A half-life problem is just decay with a known rate.

Key idea: The rate r controls the steepness. The exponent rt or nt is time multiplied by how fast the process happens.

Logarithms

Logarithms and change of base

Logarithms undo exponents. If b^y = x, then log_b(x) = y. They are useful when you know the final amount and want the time.

Most programming languages only have natural log ln and log base 10. The change-of-base formula lets you compute any base:

log_b(x) = ln(x) / ln(b)

For continuous growth A = Pe^(rt), solving for t gives:

t = ln(A/P) / r

Interactive

Interactive growth calculator

Enter a principal, rate, and time. The tool will compute compound and continuous growth, and show how to solve for time using a logarithm.


    
Code It

Exponents and logs in Python

These functions handle the most common exponential questions: grow, decay, compound, and solve for time.

exponents.py
import math

def compound_interest(P, r, n, t):
    return P * (1 + r / n)**(n * t)

def continuous_growth(P, r, t):
    return P * math.exp(r * t)

def log_base(x, b):
    return math.log(x) / math.log(b)

def solve_for_time(P, A, r):
    # A = P * e^(rt)  =>  t = ln(A/P) / r
    return math.log(A / P) / r

print(compound_interest(1000, 0.05, 12, 10))
print(solve_for_time(1000, 2000, 0.05))
Output
1647.0094976908335
13.862943611198906

Notice how solve_for_time rearranges the growth formula. Code lets you solve for any variable once you know the formula's structure.

Check Yourself

Quick quiz

1. What does a logarithm undo?

2. In A = Pe^(rt), what is e?

3. What happens to a quantity when r is negative in A = Pe^(rt)?

Keep learning

Exponents and logarithms handle growth and time. Next, use code to work with vectors and matrices, the building blocks of graphics and machine learning.

Part of the “Coding for High School Math” series.