Skip to main content

Wolfram

Welcome to Wolfram Language

Wolfram Language is a powerful computational language developed by Wolfram Research. Unlike traditional programming languages, it's a knowledge-based language with built-in access to vast computational capabilities, algorithms, and real-world data. It powers Wolfram Mathematica and Wolfram|Alpha, providing a unique environment where programming meets computational intelligence.

Key features include:

  • Built-in computational knowledge across thousands of domains
  • Symbolic computation capabilities
  • Integrated data science and visualization
  • Seamless access to curated data
  • Natural language understanding through Wolfram|Alpha integration

Introduction to Wolfram Language

Wolfram Language provides multiple ways to get started, from desktop applications to cloud-based access.

Access Methods

  1. Wolfram Mathematica: Full desktop environment with notebook interface
  2. Wolfram Cloud: Browser-based access through cloud.wolfram.com
  3. Wolfram|Alpha: Natural language queries at wolframalpha.com
  4. Wolfram Engine: Free engine for developers

Your First Computation

In Wolfram Language, computations can be as simple as typing natural language or using precise syntax:

2 + 2
(* Output: 4 *)
Expand[(x + y)^3]
(* Output: x^3 + 3x^2y + 3xy^2 + y^3 *)
Plot[Sin[x], {x, 0, 2Pi}]

The language is designed to be intuitive while providing extremely powerful computational capabilities.

Wolfram Language Syntax

1. Function Calls (Square Brackets)

Wolfram Language uses square brackets [ ] for function arguments, unlike parentheses in most languages:

Sin[Pi/2]          (* Correct *)
Sin(Pi/2)          (* Incorrect - will not work *)

2. Comments

Comments are enclosed in (* ... *):

(* This is a comment *)
result = 2 + 2     (* This computes the sum *)

3. Pattern Matching

Patterns use underscores and are fundamental to Wolfram Language:

f[x_] := x^2       (* Define function for any x *)
f[5]               (* Returns 25 *)

4. List Construction

Lists use curly braces { }:

myList = {1, 2, 3, 4, 5}
first = myList[[1]]   (* List indexing uses double brackets *)

5. Rules and Associations

Rules use -> and associations use <| ... |>:

rule = x -> 5                (* Replacement rule *)
assoc = <|"a" -> 1, "b" -> 2|>  (* Association (key-value store) *)

Basic Computation

Wolfram Language handles both exact and approximate computation seamlessly.

Exact Computation

1/2 + 1/3
(* Output: 5/6 - exact fraction *)

Sqrt[8]
(* Output: 2√2 - exact symbolic form *)

Numerical Approximation

N[1/2 + 1/3]      (* Force numerical evaluation *)
(* Output: 0.833333 *)

Sqrt[8] // N      (* Alternative syntax *)
(* Output: 2.82843 *)

Unit Computation

Quantity[10, "Meters"] / Quantity[2, "Seconds"]
(* Output: 5 m/s *)

UnitConvert[%, "Miles"/"Hours"]
(* Output: 11.1847 mph *)

Date Computation

Today + Quantity[100, "Days"]
(* Output: Date object 100 days from today *)

Arithmetic Operations

Basic arithmetic with exact and numerical results.

(* Basic operations *)
7 + 3 - 2 * 4 / 2
(* Output: 6 *)

2^10                (* Exponentiation *)
(* Output: 1024 *)

Factorial[10]       (* 10! *)
(* Output: 3628800 *)

Mod[17, 5]          (* Modulo operation *)
(* Output: 2 *)

Mathematical Constants

Pi                  (* π *)
E                   (* Euler's number *)
I                   (* Imaginary unit *)
Degree              (* π/180 for degree conversion *)
Infinity            (* ∞ *)

Numerical Precision Control

N[Pi]               (* Default precision *)
(* Output: 3.14159 *)

N[Pi, 50]           (* 50 digits of precision *)
(* Output: 3.1415926535897932384626433832795028841971693993751 *)

Equation Solving

Wolfram Language provides powerful equation solving capabilities.

Algebraic Equations

Solve[x^2 + 2x - 8 == 0, x]
(* Output: {{x -> -4}, {x -> 2}} *)

Solve[{2x + y == 5, x - y == 1}, {x, y}]
(* Output: {{x -> 2, y -> 1}} - system of equations *)

Numerical Solving

NSolve[x^5 - x - 1 == 0, x]
(* Output: Numerical roots of the equation *)

FindRoot[Sin[x] == x/2, {x, 1}]
(* Output: {x -> 1.89549} - numerical root finding *)

Differential Equations

DSolve[y'[x] == y[x], y[x], x]
(* Output: {{y[x] -> E^x C[1]}} *)

DSolve[{y''[x] + y[x] == 0, y[0] == 1, y'[0] == 0}, y[x], x]
(* Output: {{y[x] -> Cos[x]}} - with boundary conditions *)

Calculus Operations

Differentiation

D[x^3 + 2x^2 - x + 5, x]
(* Output: -1 + 4x + 3x^2 *)

D[Sin[x * Cos[x]], x]
(* Output: Cos[x Cos[x]] (Cos[x] - x Sin[x]) *)

Integration

Integrate[x^2, x]
(* Output: x^3/3 *)

Integrate[Sin[x], {x, 0, Pi}]
(* Output: 2 - definite integral *)

Integrate[Exp[-x^2], {x, -Infinity, Infinity}]
(* Output: √π *)

Limits and Series

Limit[Sin[x]/x, x -> 0]
(* Output: 1 *)

Series[Exp[x], {x, 0, 5}]
(* Output: 1 + x + x^2/2 + x^3/6 + x^4/24 + x^5/120 + O[x]^6 *)

Linear Algebra

Matrix Operations

A = {{1, 2}, {3, 4}};
B = {{5, 6}, {7, 8}};

A . B               (* Matrix multiplication *)
(* Output: {{19, 22}, {43, 50}} *)

Inverse[A]          (* Matrix inverse *)
(* Output: {{-2, 1}, {3/2, -(1/2)}} *)

Det[A]              (* Determinant *)
(* Output: -2 *)

Eigenvalues[A]      (* Eigenvalues *)
(* Output: {1/2(5-√33), 1/2(5+√33)} *)

Vector Operations

v = {1, 2, 3};
w = {4, 5, 6};

v . w               (* Dot product *)
(* Output: 32 *)

Cross[v, w]         (* Cross product *)
(* Output: {-3, 6, -3} *)

Norm[v]             (* Vector norm *)
(* Output: √14 *)

Special Functions

Wolfram Language includes hundreds of special mathematical functions.

Gamma[5]            (* Gamma function *)
(* Output: 24 *)

Zeta[2]             (* Riemann zeta function *)
(* Output: π^2/6 *)

BesselJ[1, 2.5]     (* Bessel function *)
(* Output: 0.497095 *)

Erf[1]              (* Error function *)
(* Output: 0.842701 *)

Numbers and Precision

Number Types

123                 (* Integer *)
123.456             (* Real (approximate number) *)
1 + 2I              (* Complex number *)
1/3                 (* Rational number *)

Arbitrary Precision

N[Pi, 100]          (* 100 digits of π *)
(* Output: 3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117068 *)

Precision[123.456]  (* Check precision *)
(* Output: MachinePrecision *)

Symbols and Variables

Symbolic Computation

x + x               (* Symbolic addition *)
(* Output: 2x *)

y = x^2 + 2x + 1;   (* Assignment *)
Expand[y]           (* Expand expression *)
(* Output: 1 + 2x + x^2 *)

Assumptions

Simplify[Sqrt[x^2], x > 0]
(* Output: x *)

Refine[Abs[x], x ∈ Reals && x < 0]
(* Output: -x *)

Lists - General

List Creation

list1 = {1, 2, 3, 4, 5};
list2 = Range[10]    (* {1, 2, 3, ..., 10} *)
list3 = Table[i^2, {i, 1, 5}]  (* {1, 4, 9, 16, 25} *)

List Operations

Length[list1]        (* 5 *)
First[list1]         (* 1 *)
Last[list1]          (* 5 *)
Rest[list1]          (* {2, 3, 4, 5} *)

List Operations

Element Manipulation

list = {a, b, c, d, e};

list[[3]]            (* Get third element: c *)
Append[list, f]      (* {a, b, c, d, e, f} *)
Prepend[list, z]     (* {z, a, b, c, d, e} *)
Insert[list, x, 3]   (* {a, b, x, c, d, e} *)

Functional Operations

Map[f, {1, 2, 3}]    (* {f[1], f[2], f[3]} *)
f /@ {1, 2, 3}       (* Shorthand syntax *)

Select[{1, 2, 3, 4, 5}, # > 2 &]  (* {3, 4, 5} *)

Array Operations

Multi-dimensional Arrays

matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
matrix[[2, 3]]       (* Get element: 6 *)
Dimensions[matrix]   (* {3, 3} *)

ArrayReshape[Range[12], {3, 4}]
(* Creates 3x4 matrix *)

Associations - General

Associations are key-value stores (similar to dictionaries in Python).

assoc = <|"name" -> "Alice", "age" -> 30, "city" -> "Boston"|>;
assoc["name"]        (* Access value: Alice *)

<|assoc, "country" -> "USA"|>  (* Add key *)
KeyDrop[assoc, "city"]         (* Remove key *)

Association Functions

assoc = <|"a" -> 1, "b" -> 2, "c" -> 3|>;

Keys[assoc]          (* {"a", "b", "c"} *)
Values[assoc]        (* {1, 2, 3} *)
KeyExistsQ[assoc, "b"]  (* True *)

AssociationMap[#^2 &, {"x", "y", "z"}]
(* Output: <|"x" -> x^2, "y" -> y^2, "z" -> z^2|> *)

String Operations

str = "Hello World";

StringLength[str]    (* 11 *)
StringTake[str, 5]   (* "Hello" *)
StringContainsQ[str, "World"]  (* True *)

StringJoin["Hello", " ", "World"]  (* "Hello World" *)
StringSplit["a,b,c", ","]          (* {"a", "b", "c"} *)

Patterns and Rule-based Programming

(* Pattern matching in function definitions *)
f[x_Integer] := "Integer"
f[x_Real] := "Real"
f[_] := "Other"

f[5]    (* "Integer" *)
f[2.5]  (* "Real" *)
f["a"]  (* "Other" *)

(* Replacement rules *)
{x, y, z} /. x -> 5          (* {5, y, z} *)
{x, y, z} /. {x -> 1, y -> 2}  (* {1, 2, z} *)

Variables and Assignment

Immediate vs. Delayed Assignment

x = 5               (* Immediate assignment *)
y := RandomReal[]   (* Delayed assignment - evaluated each time *)

f[x_] = x^2         (* Immediate function definition *)
g[x_] := x^2        (* Delayed function definition *)

Clearing Variables

Clear[x]            (* Remove value but keep symbol *)
Remove[x]           (* Completely remove symbol *)
ClearAll["Global`*"] (* Clear all user-defined symbols *)

Function Definitions

Basic Function Definitions

(* Standard function *)
f[x_] := x^2 + 2x + 1

(* Function with multiple arguments *)
g[x_, y_] := x^2 + y^2

(* Function with conditions *)
h[x_] := x^2 /; x > 0  (* Only defined for x > 0 *)
h[x_] := 0 /; x <= 0

Optional Arguments and Patterns

(* Function with optional argument *)
process[x_, opts___] := Module[{y = x}, y]

(* Function with default value *)
format[text_, style_:"Standard"] := Style[text, style]

Conditional Logic

(* If statement *)
result = If[x > 0, "Positive", "Non-positive"]

(* Which statement - multiple conditions *)
grade = Which[
  score >= 90, "A",
  score >= 80, "B", 
  score >= 70, "C",
  True, "F"   (* default case *)
]

(* Switch statement *)
dayName = Switch[day,
  1, "Monday", 2, "Tuesday", 3, "Wednesday",
  4, "Thursday", 5, "Friday", 6, "Saturday", 
  7, "Sunday"
]

Looping Constructs

Iteration Functions

(* Do loop - iteration without return value *)
Do[Print[i], {i, 1, 5}]

(* For loop - traditional looping *)
For[i = 1, i <= 5, i++, Print[i]]

(* While loop *)
i = 1;
While[i <= 5, Print[i]; i++]

(* Table - functional iteration with results *)
Table[i^2, {i, 1, 5}]  (* {1, 4, 9, 16, 25} *)

Pure Functions

(#^2 &)[5]           (* 25 *)
Function[x, x^2][5]  (* 25 - equivalent *)

Map[#^2 &, {1, 2, 3, 4}]  (* {1, 4, 9, 16} *)

(* Pure function with multiple arguments *)
#1 + #2 &[3, 4]     (* 7 *)

Select[{1, 2, 3, 4, 5}, # > 2 &]  (* {3, 4, 5} *)

Functional Programming

(* Map application *)
f /@ {1, 2, 3}       (* {f[1], f[2], f[3]} *)

(* Apply function to list *)
Apply[Plus, {1, 2, 3, 4}]   (* 10 *)
Plus @@ {1, 2, 3, 4}        (* 10 - shorthand *)

(* Fold - cumulative application *)
Fold[#1 + #2 &, 0, {1, 2, 3, 4}]  (* 10 *)

(* Nest - repeated application *)
Nest[f, x, 3]        (* f[f[f[x]]] *)

Plotting and Visualization

Basic Plotting

Plot[Sin[x], {x, 0, 2Pi}]

Plot3D[Sin[x y], {x, -Pi, Pi}, {y, -Pi, Pi}]

ListPlot[{1, 4, 2, 8, 5}]

Customized Plots

Plot[Sin[x], {x, 0, 2Pi}, 
 PlotLabel -> "Sine Wave",
 AxesLabel -> {"x", "Sin[x]"},
 GridLines -> Automatic,
 PlotStyle -> Red]

Multiple Plots

Plot[{Sin[x], Cos[x]}, {x, 0, 2Pi},
 PlotLegends -> {"Sin", "Cos"}]

Data Import and Export

(* Import CSV data *)
data = Import["data.csv"]

(* Import from URL *)
webdata = Import["https://example.com/data.json"]

(* Export data *)
Export["output.csv", data]

(* Work with common formats *)
ImportString["1,2,3\n4,5,6", "CSV"]
(* Output: {{1, 2, 3}, {4, 5, 6}} *)

Knowledge Access

Wolfram Language has built-in access to vast curated data.

(* Chemical data *)
ElementData["Carbon", "AtomicNumber"]  (* 6 *)

(* Geographical data *)
CityData["Chicago", "Population"]

(* Mathematical data *)
PolyhedronData["Icosahedron", "Volume"]

(* Physical constants *)
PlanckConstant

(* Financial data *)
FinancialData["AAPL", "Price"]

Python Integration

Wolfram Language can interoperate with Python using ExternalEvaluate.

(* Evaluate Python code *)
ExternalEvaluate["Python", "2 + 2"]
(* Output: 4 *)

(* Use Python libraries *)
ExternalEvaluate["Python", "import math; math.sqrt(16)"]
(* Output: 4.0 *)

(* Pass data between systems *)
ExternalEvaluate["Python", "len([1, 2, 3])"]
(* Output: 3 *)

Using Wolfram Client Library for Python:

# Python code using Wolfram Client Library
from wolframclient.evaluation import WolframLanguageSession
from wolframclient.language import wl

session = WolframLanguageSession()
session.evaluate(wl.Range(5))  # [1, 2, 3, 4, 5]
session.terminate()

Wolfram Alpha API Access

Access Wolfram Alpha computational knowledge through API.

(* Natural language queries *)
WolframAlpha["population of France", "Result"]
(* Output: 67.8 million people (latest value) *)

WolframAlpha["distance from Earth to Moon", "Result"]
(* Output: 238855 miles *)

(* Step-by-step solutions *)
WolframAlpha["solve x^2 + 2x - 8 = 0", "Step-by-step solution"]

Python API Example:

import wolframalpha

client = wolframalpha.Client('YOUR_APP_ID')
res = client.query('population of France')
answer = next(res.results).text
print(answer)  # 67.8 million people

Advanced Topics

Parallel Computing

ParallelTable[PrimeQ[i], {i, 10^10, 10^10 + 100}]
ParallelMap[FactorInteger, Range[100, 150]]

Machine Learning

(* Classify data *)
training = {1 -> "A", 2 -> "B", 3 -> "A", 4 -> "B"};
c = Classify[training]
c[2.5]  (* "A" *)

(* Predict numerical values *)
p = Predict[{1 -> 1.2, 2 -> 2.3, 3 -> 3.1}]
p[2.5]  (* 2.7 *)

Image Processing

img = Import["image.jpg"];
ColorNegate[img]
EdgeDetect[img]
ImageIdentify[img]  (* Identify objects in image *)