Applied Precalculus / Online editionResources

Getting Started with R and Python

Purpose. This appendix is a practical, beginner-friendly reference for the computational activities throughout this book. You do not need previous programming experience. The goal is to understand the mathematics first, then use a small amount of code to calculate, visualize, check, and explain your results. The two sections cover the same essential skills so that you can work in either language or compare both.

Getting Started with R

A.1 What is R, and what do I need?

R is a free programming language designed for numerical analysis, statistics, and graphics. R is the language; RStudio is an optional development environment that makes it easier to edit and run R scripts. Install R from https://cran.r-project.org/, then optionally install RStudio Desktop from https://posit.co/download/rstudio-desktop/. Follow your operating system’s installation instructions. In RStudio, you can type short commands in the Console, but save reusable code in a script (File > New File > R Script). Save a script with the extension .R. Select a line or lines and use the Run command, or use Source to run the entire script. For a first exercise, type:

R
2 + 3
sqrt(49)
pi

You should obtain 5, 7, and an approximation to \(\pi\). If an error appears, read the message carefully: R is case-sensitive, so Sqrt(49) is not the same as sqrt(49).

A.2 Arithmetic, variables, and comments

R uses +, -, *, /, and ^ for addition, subtraction, multiplication, division, and powers. Parentheses control the order of operations. Assign a value with <-; a # starts a comment that R ignores.

R
# A circle with radius 4 centimeters
radius <- 4
area <- pi * radius^2
circumference <- 2 * pi * radius
print(area)
print(circumference)

Interpretation. The calculated area is measured in square centimeters, whereas circumference is measured in centimeters. Code returns numbers, but you must supply and check the units. Try it: change the radius to 6. Predict the factor by which the area changes before running the code. Answer: \((6/4)^2=2.25\).

A.3 Vectors, sequences, and tables

A vector stores several values of the same basic type. Use c() to combine values, seq() to create a sequence, and data.frame() to assemble a table. R’s vector indices begin at 1.

R
t <- c(0, 1, 2, 3, 4)
concentration <- 80 * (0.75)^t
measurements <- data.frame(time_hours = t,
                           concentration = concentration)
print(measurements)
print(concentration[1]) # first observation

The concentration is modeled by \(C(t)=80(0.75)^t\). This is a hypothetical example. The multiplier 0.75 means that 75% of the previous amount remains after each hour. Try it: replace t with seq(0, 8, by = 0.5) and observe how the table changes.

A.4 Functions and function evaluation

A function takes an input and returns an output. Mathematical notation \(f(x)=x^2-4x+3\) corresponds to the following R definition:

R
f <- function(x) {
  x^2 - 4*x + 3
}
print(f(2))
x <- seq(-1, 5, by = 0.5)
print(data.frame(x = x, f_x = f(x)))

R automatically applies arithmetic operations to each element of a numeric vector. Note that multiplication must be written explicitly as 4*x. Check by hand: \(f(2)=4-8+3=-1\).

A.5 Plotting a function

The following example uses base R, so no extra package is required. Always include axis labels, appropriate units, and a descriptive title.

R
f <- function(x) x^2 - 4*x + 3
x <- seq(-1, 5, length.out = 301)
plot(x, f(x), type = "l", lwd = 2,
     xlab = "x", ylab = "f(x)",
     main = "Quadratic function")
abline(h = 0, v = 0, col = "gray70")
points(c(1, 3), c(0, 0), pch = 19)

The graph crosses the horizontal axis at \(x=1\) and \(x=3\), consistent with \(f(x)=(x-1)(x-3)\). A plotted curve is evidence to explore; algebra verifies the exact zeros. Figure quality checklist: readable axes, correct units, sufficient sampling resolution, visible important features, and a caption that explains the mathematical takeaway.

A.6 Trigonometry and radians

R’s sin(), cos(), and tan() functions expect angles in radians. Convert degrees using \(\theta_{\mathrm{rad}}=\theta_{\mathrm{deg}}\pi/180\).

R
angle_deg <- 30
angle_rad <- angle_deg * pi / 180
print(sin(angle_rad)) # 0.5
angles <- seq(0, 2*pi, length.out = 401)
plot(angles, sin(angles), type = "l",
     xlab = "Angle (radians)", ylab = "sin(angle)",
     main = "One complete sine cycle")

A common mistake is to type sin(30) and assume that R interprets 30 degrees. It does not.

A.7 Solving equations numerically

Use algebra whenever possible, then use numerical methods to check or approximate solutions. The uniroot() function finds a zero within an interval whose endpoints have opposite signs (for a continuous function).

R
g <- function(x) x^3 - x - 2
print(g(1))
print(g(2))
root <- uniroot(g, interval = c(1, 2))$root
print(root)
print(g(root))

The numerical root is approximately 1.52138. The final residual \(g(\text{root})\) should be close to zero. A small residual is useful but is not, by itself, a proof of uniqueness.

A.8 Data, basic model fitting, and residuals

A residual is observed minus predicted. In this example we fit a straight line to illustrative calibration measurements.

R
x <- c(0, 1, 2, 3, 4)
y <- c(1.1, 2.9, 5.2, 7.0, 9.1)
fit <- lm(y ~ x)
predicted <- predict(fit)
residual <- y - predicted
print(data.frame(x, y, predicted, residual))
plot(x, y, pch = 19, xlab = "Input (units)",
     ylab = "Response (units)", main = "Calibration")
abline(fit, lwd = 2)

The fitted line summarizes the relationship; it does not guarantee that the model is appropriate outside the observed input range. Ask whether residuals show a pattern, whether units make sense, and whether extrapolation is justified.

A.9 Common errors and good habits

R practice task. Create a table and graph of \(h(t)=120(0.8)^t\) for \(t=0,1,\ldots,10\). Find the first integer \(t\) for which \(h(t)<30\). Check the result algebraically using logarithms. Check: \(t=7\).

Getting Started with Python

B.1 What is Python, and what do I need?

Python is a general-purpose programming language widely used in science, engineering, and data analysis. Download Python from https://www.python.org/downloads/. You may work in a Python editor or notebook (for example, IDLE, VS Code, or Jupyter). For this textbook, a basic editor that can run .py files is sufficient. Some later laboratories use the numpy and matplotlib libraries; install them from a terminal with python -m pip install numpy matplotlib. On systems where the Python command is python3, use python3 -m pip install numpy matplotlib instead. Installation steps can vary by operating system.

Python
print(2 + 3)
print(49**0.5)

You should see 5 and 7.0. Python uses ** for powers, not ^. A # begins a comment. Save reusable scripts with the extension .py.

B.2 Arithmetic, variables, and the math library

Python
import math
# A circle with radius 4 centimeters
radius = 4
area = math.pi * radius**2
circumference = 2 * math.pi * radius
print(area)
print(circumference)

import math makes functions and constants such as math.sqrt, math.log, and math.pi available. Python uses = for assignment; use == to test equality. Try it: change the radius to 6 and compare the areas, then explain why the ratio is 2.25.

B.3 Lists, loops, and tables

A list holds multiple values. Python indices begin at 0. A for loop can repeat a calculation; the indented lines form the loop body.

Python
times = [0, 1, 2, 3, 4]
concentrations = [80 * (0.75**t) for t in times]
for t, c in zip(times, concentrations):
    print(f"time={t} h, concentration={c:.2f}")
print(concentrations[0]) # first observation

This computes the same hypothetical model \(C(t)=80(0.75)^t\) used in the R section. A list comprehension such as [expression for t in times] creates a new list from repeated calculations. Try it: use range(9) to produce times from 0 through 8.

B.4 Functions and evaluation

Python functions are defined using def; indentation is required. The return statement supplies the function’s output.

Python
def f(x):
    return x**2 - 4*x + 3

print(f(2))
for x in [-1, 0, 1, 2, 3, 4, 5]:
    print(x, f(x))

Check by hand that \(f(2)=-1\) and factor \(f(x)\) to find its zeros. In contrast with R, applying a function written for a single number to an ordinary Python list requires a loop or comprehension.

B.5 Arrays and plotting with NumPy and Matplotlib

NumPy arrays support elementwise mathematical calculations. Matplotlib produces graphs. The following complete script plots the same quadratic as the R example.

Python
import numpy as np
import matplotlib.pyplot as plt

def f(x):
    return x**2 - 4*x + 3

x = np.linspace(-1, 5, 301)
plt.plot(x, f(x), linewidth=2, label="f(x)")
plt.scatter([1, 3], [0, 0], label="Zeros")
plt.axhline(0, color="gray", linewidth=0.7)
plt.xlabel("x")
plt.ylabel("f(x)")
plt.title("Quadratic function")
plt.legend()
plt.tight_layout()
plt.show()

np.linspace(-1,5,301) produces 301 equally spaced inputs from \(-1\) to 5. The show() call displays the figure in a standard Python script. To save a publication-quality image, call plt.savefig("quadratic.png", dpi=300) before plt.show().

B.6 Trigonometry and radians

Python’s math.sin() and NumPy’s np.sin() both expect radians.

Python
import math
import numpy as np
import matplotlib.pyplot as plt

angle_deg = 30
angle_rad = math.radians(angle_deg)
print(math.sin(angle_rad)) # approximately 0.5
angles = np.linspace(0, 2*np.pi, 401)
plt.plot(angles, np.sin(angles))
plt.xlabel("Angle (radians)")
plt.ylabel("sin(angle)")
plt.title("One complete sine cycle")
plt.tight_layout()
plt.show()

The conversion math.radians(30) is equivalent to \(30\pi/180\). Never assume a trigonometric function uses degrees.

B.7 Numerical solutions without extra packages

Bisection is a reliable way to approximate a root of a continuous function when a sign change is known. It repeatedly halves an interval containing the root.

Python
def g(x):
    return x**3 - x - 2

a, b = 1.0, 2.0
assert g(a) * g(b) < 0
for step in range(40):
    mid = (a + b) / 2
    if g(a) * g(mid) <= 0:
        b = mid
    else:
        a = mid
root = (a + b) / 2
print(root)
print(g(root))

The root is approximately 1.52138. The loop is an implementation of the mathematical interval-halving procedure; it does not replace understanding why the sign-change condition matters.

B.8 Data, linear models, and residuals

The following example uses NumPy to fit a straight line to the same illustrative calibration data used in R.

Python
import numpy as np
import matplotlib.pyplot as plt

x = np.array([0, 1, 2, 3, 4], dtype=float)
y = np.array([1.1, 2.9, 5.2, 7.0, 9.1])
slope, intercept = np.polyfit(x, y, 1)
predicted = slope*x + intercept
residuals = y - predicted
print("slope:", slope, "intercept:", intercept)
print("residuals:", residuals)
plt.scatter(x, y, label="Observed")
plt.plot(x, predicted, label="Fitted line")
plt.xlabel("Input (units)")
plt.ylabel("Response (units)")
plt.legend()
plt.tight_layout()
plt.show()

Compare the slope and intercept with those obtained from lm(y   x) in R. Small differences caused by rounding are expected, but both programs should fit the same least-squares line.

B.9 Common errors and good habits

Python practice task. Create a table and graph of \(h(t)=120(0.8)^t\) for \(t=0,1,\ldots,10\). Find the first integer \(t\) for which \(h(t)<30\) and verify the result algebraically. Check: \(t=7\).

B.10 Moving between R and Python

Task R Python
Assign a variable x <- 3 x = 3
Power x2̂ x**2
Square root sqrt(x) math.sqrt(x)
Natural logarithm log(x) math.log(x)
Create values c(1,2,3) [1,2,3]
Sequence seq(0,1,by=.1) np.linspace(0,1,11)
First item x[1] x[0]
Display output print(x) print(x)

B.11 A repeatable workflow for every laboratory

  1. State the mathematical question. Identify the unknown quantity, assumptions, domain, and units.

  2. Predict before computing. Estimate a value, graph shape, or direction of change by hand.

  3. Run the complete code. Use the chapter’s code/chXX/ script or type the listing carefully.

  4. Inspect output critically. Check axes, units, numerical precision, restrictions, and possible errors.

  5. Verify independently. Substitute an answer into the original expression or compare with an algebraic result.

  6. Interpret in words. State what the result means in context and where the model may fail.

Final reminder. Code is a tool for mathematical exploration. A convincing mathematical explanation identifies the relevant properties, shows the reasoning, and interprets the result; a screenshot or numerical answer alone is not enough.