Math Functions & Random Numbers

16.1 Built-in math functions

sign: -1, 0, or 1 SGN(-7) → -1 EXP(1) → 2.718...

natural logarithm (ln) LOG(EXP(2)) → 2 SIN, COS, TAN trig (radians) SIN(_PI / 2) → 1 arctangent (radians) 4 * ATN(1) → π _ATAN2(y, x) angle of vector (QB64) full -π..π range _ACOS, _ASIN inverse cosine / sine (QB64) _HYPOT(x, y) √(x² + y²) (QB64) _D2R(d) / _R2D(r) degrees ↔ radians (QB64) INT(x) / FIX(x) floor / truncate _CEIL(x) / _ROUND(x) ceiling / round (QB64) CINT, CLNG round to INTEGER / LONG Derived formulas:

log10 = LOG(x) / LOG(10)
cubeRoot = SGN(x) * ABS(x) ^ (1 / 3)
roundTo2 = INT(x * 100 + 0.5) / 100
degrees = radians * 180 / _PI
distance = SQR((x2 - x1) ^ 2 + (y2 - y1) ^ 2)

16.2 Random numbers: RND and RANDOMIZE

RND returns a pseudo-random SINGLE in the range 0 ≤ RND < 1. Without seeding, the sequence is the same every run.

RND(0) repeats the last number; RND with a negative argument reseeds. QB64 adds RANDOMIZE USING seed to restart a sequence exactly.

RANDOMIZE TIMER                         ' seed from the clock (do this once)
PRINT RND                               ' 0.0 to 0.9999...
die = INT(RND * 6) + 1                  ' integer 1..6
coin$ = MID$("HT", INT(RND * 2) + 1, 1) ' "H" or "T"
r = lo + INT(RND * (hi - lo + 1))       ' integer lo..hi inclusive
f = lo + RND * (hi - lo)                ' real lo..hi
RANDOMIZE 42                            ' fixed seed: reproducible sequence (useful for testing)

16.3 Floating-point precision

SINGLE holds about 7 significant digits — use DOUBLE for money totals, science, and accumulations.

Never compare floats for exact equality; compare the difference against a tolerance: IF ABS(a - b) < 0.000001 THEN.

For exact money arithmetic, store whole cents in a LONG or _INTEGER64.

Classic BASIC: RND(1) (argument required in many BASICs); Commodore RND(-TI) seeded from the clock; Sinclair RANDOMIZE. LOG is natural log everywhere; some BASICs had LOG10. FreeBASIC: Randomize Timer, Rnd, Sqr, Atan2, Log, Exp, Int, Fix, Frac; constant pi via Const PI = 4 * Atn(1). VB.NET: Math.Sqrt, Math.Sin, Math.Atan2, Math.PI, Math.Round(x, 2), Math.Log10; random numbers with Dim rng As New Random() and rng.Next(1, 7) (upper bound exclusive), or Random.Shared.Next(...) on .NET 6+.