Numbers: Exact and Approximate
Prerequisites: Your first program
The Wolfram Language keeps numbers exact unless you ask for a decimal approximation.
1/3 + 1/6
10/4
10/4.
N[10/4]
Sqrt[8]
2^100
1/2
5/2
2.5
2.5
2 Sqrt[2]
1267650600228229401496703205376
- Integers and fractions (rationals) stay exact, however large.
- A number with a decimal point, like
4., is approximate, and so is any result it touches. N[expr]gives a numerical approximation.Sqrt[8]simplifies to2 Sqrt[2]— still exact.
Arbitrary precision
N[Pi]
N[Pi, 30]
N[Sqrt[2], 20]
3.14159
3.14159265358979323846264338328
1.4142135623730950488
N[expr, n] computes n significant digits — as many as you like.
N[Pi] is a normal machine-precision number (about 16 digits); the
notebook just displays six.
Integer operations
Quotient[17, 5]
Mod[17, 5]
20!
FactorInteger[360]
Prime[10]
PrimeQ[2^31 - 1]
GCD[12, 18]
3
2
2432902008176640000
{{2, 3}, {3, 2}, {5, 1}}
29
True
6
FactorInteger[360] means 360 = 2³ × 3² × 5.
Rounding
Round[2.5]
Round[3.5]
Floor[-2.5]
Ceiling[2.1]
Round[3.14159, 0.01]
2
4
-3
3
3.14
Round rounds halves to the nearest even integer, so 2.5 becomes
2.
Constants and functions
Built-in constants and functions use capital letters: Pi, E, I
(the imaginary unit), Infinity, Degree.
Sin[Pi/6]
Sin[30 Degree]
Log[E]
Log[10, 1000]
Sqrt[-4]
1/2
1/2
1
3
2 I
Trigonometric functions use radians; multiply by Degree to use
degrees. Log[b, x] is the logarithm to base b.
Common mistakes
- Writing
sin(x)— it'sSin[x]: capital letter, square brackets. Parentheses only group. - Expecting
1/3to give0.333333— it stays1/3. UseN[1/3]or1/3..
Practice
Compute 2 to the power 64 exactly, and e (the constant E) to 20
digits.
Show solution
2^64
N[E, 20]
18446744073709551616
2.7182818284590452354