Givens row-pair update 2026-10-14
Left matrix multiplication by a Givens rotation replaces rows of a matrix byBoth right-hand sides use the old entries. An in-place algorithm must save the first result temporarily, update the second entry, and only then overwrite the first. The reference BLAS
DROT implementation follows this order with its temporary DTEMP.[ref]DROT (Reference BLAS, LAPACK 3.12.1) by LAPACK project. DROT source, lines 116–120 and 130–134: temporary first-row value and second-row update
For elimination in column , construct from . This sets the lower component to zero in exact arithmetic. In floating-point arithmetic the computed expression can leave a small remainder; after computing the other updated entries, explicitly store and . Previously eliminated columns stay zero if both participating rows are already zero there. This is why the ordering in QR decomposition by Givens rotations matters.
Gram-Schmidt process Created 2026-09-24 Updated 2026-10-14
The Gram-Schmidt process turns a finite ordered family of linearly independent vectors in an inner product space over the real numbers into an orthonormal basis of their linear span. It keeps every successive linear span, so the first new vectors describe exactly the same directions as the first inputs. Its idea is geometric: remove the orthogonal projection onto directions already found, then divide the remaining vector by its norm. This makes a complicated basis easier to use without changing the vector subspace it describes.[ref]
Start with and . At step , use the previously obtained orthonormal set to defineThe sum is the orthogonal projection onto a finite-dimensional subspace , and is the orthogonal projection residual. Linear independence ensures : otherwise would already be a linear combination of earlier inputs. If the input family is linearly dependent, use only the retained orthonormal vectors in the sum and omit an input whenever its remainder is the zero vector; do not divide by zero. The retained outputs still form an orthonormal basis of the original linear span, but their number can be smaller than .
For a short verification, orthonormality makes every earlier inner product vanish:Also is minus a linear combination of earlier vectors, while is plus that same linear combination. These two inclusions, followed by division by a nonzero norm, giveThe argument also works in an inner product space over the complex numbers with the existing inner product convention, linear in the first argument: the coefficients remain . With the convention linear in the second argument, write instead.
For a first picture, take and in with the ordinary dot product. ThenSubtracting the diagonal component leaves an orthogonal direction; dividing by its norm makes its length one. If the second input were instead, its orthogonal projection would be the entire input and , revealing linear dependence.
Gram-Schmidt orthogonalization in : input vectors, subtraction of an orthogonal projection, and an orthonormal basis
. Details. For a full three-dimensional calculation, use the ordinary dot product and the input vectorsThe first two steps giveAt the third step, the inner products are and . ConsequentlyThe three numerator vectors have pairwise dot products and squared Euclidean norms . Thus the displayed outputs are indeed an orthonormal basis, and the three nonzero remainders also confirm linear independence of the inputs. Keeping the removed coefficients produces the QR decomposition below.
An immediate reward is a reusable orthogonal projection: once an orthonormal basis of a vector subspace is known, any vector hasFor the linear span of just the first two inputs in the three-dimensional example, gives . Its orthogonal projection residual is , visibly in the missing orthogonal direction. This is the geometry behind the linear least-squares problem.
The formulas above describe exact arithmetic. With floating-point arithmetic, subtracting an orthogonal projection nearly equal to the input can leave a small remainder; dividing by its small norm can magnify existing roundoff error. The Classical Gram-Schmidt and Modified Gram-Schmidt arrangements agree in exact arithmetic but can give different rounded results. Exact linear dependence and a small computed remainder therefore require different judgments in a numerical implementation.[ref]
https://nhigham.com/wp-content/uploads/2023/10/high95m.pdf. Higham, The Test Matrix Toolbox for Matlab, §8, p. 22
Householder reflection sending a vector to a coordinate axis Created 2026-10-14 Updated 2026-10-20
For a nonzero real vector , choose with and put . When , the Householder reflectionsatisfies : every component except the first becomes zero. Here is the first Cartesian basis vector. The calculation is short:If , the vector is already at the selected target, so the identity matrix suffices.
In floating-point arithmetic, a customary choice isThen , avoiding subtraction of nearly equal positive quantities in the first component. Either sign can be valid in exact arithmetic; the numerical choice protects the construction from catastrophic cancellation. [ref]
https://math.mit.edu/classes/18.085/summer2016/handouts/qr.pdf. Olver, Orthogonal Bases and the QR Algorithm: Householder factorization and sign selection
For , this choice gives and . Dividing by its Euclidean norm gives , exactly the normal in the geometric example.
Interval bisection Created 2026-10-07 Updated 2026-10-14
Interval bisection solves a target equation by repeatedly halving a closed interval known to contain a solution. It is the bisection method applied to , so the target becomes a zero of a function. This reduction from an equation to root finding is described in Demanet's notes.[ref]
https://ocw.mit.edu/courses/18-330-introduction-to-numerical-analysis-spring-2012/5b325bfa56a599794c7196de926844b0_MIT18_330S12_Chapter4.pdf. Laurent Demanet, MIT 18.330, Chapter 4, §4.1, pp. 1–2, 2012
Here the emphasis is on a continuous strictly increasing function: the target identifies one input, making interval bisection a way to evaluate its inverse function without an explicit inverse formula.Let be a continuous function, with and . The intermediate value theorem guarantees existence; a strictly increasing function also guarantees uniqueness. Check endpoint equality first. Otherwise, for the current root bracket , evaluate its midpoint . If , retain ; if , retain ; if , return that exact solution. These comparisons preserve the target bracket. General bisection method needs continuity and opposite signs of at the endpoints, without requiring monotonicity or a unique zero of a function; see limitations of bisection.
An original dimensionless polynomial example isHere and the derivative , so there is exactly one solution. In fact ; knowing this lets us check the computed absolute error independently of the guarantee. The first four halvings give the following exact rational numbers:
The beauty of interval bisection is that the enclosure itself supplies the certificate: one comparison removes half the possible inputs, regardless of the steepness of the function graph. In exact arithmetic, after completed halvings without exact termination, the width and the bisection error bound for the new midpoint areThe reported midpoint after update four is , rather than the last tested point . Its certified absolute error is at most , and its actual absolute error is . For a requested position tolerance , the bisection stopping criterion requires eleven halvings: ten give , while eleven giveThe actual absolute error is . The new midpoint need not be evaluated to obtain this certificate.
The signed output residual is ; the position approximation error is . They answer different questions: how close is the output to the target, and how close is the input to the solution? Driscoll and Braun explain why a small residual needs information about the derivative to imply small position error.[ref]
https://fncbook.com/rootproblem/. Toby A. Driscoll and Richard J. Braun, Fundamentals of Numerical Computation, §4.1.1, Conditioning, error, and residual
For this particular polynomial, direct factorization givesThus at the residual is , despite position absolute error . If a differentiable function satisfies throughout the bracket, the mean value theorem gives the rigorous conversionOur example permits and on . Strict increase alone supplies no positive lower derivative bound: is strictly increasing but . A small residual alone is therefore not a universal position certificate; even the target equation has residual at , a full unit from its solution.The guarantees require continuity and correct evaluations, not just narrowing endpoints. For the strictly increasing function when and when , the target lies between and but is never attained: a jump discontinuity defeats the existence argument. With floating-point arithmetic or an approximate evaluation, an incorrect comparison can discard the true solution. A certified interval enclosure of wholly below or above certifies the corresponding decision; an enclosure containing is inconclusive, rather than proof of equality. If rounding makes the midpoint equal an endpoint, report the precision limit; see bisection stopping criterion for the rounded position bound. Both figures are exact mathematical examples, not measured data.
Log-likelihood Created 2026-09-24 Updated 2026-10-14
The log-likelihood is the natural logarithm of the likelihood function:For positive finite likelihood, the natural logarithm is a strictly increasing function, so the maximizing parameter values are unchanged. Set where ; the same ordering then includes zero-likelihood boundaries whenever a positive finite maximum exists. For independent and identically distributed random variables, a product becomes a sum,This makes derivatives simpler and avoids forming products of tiny numbers in floating-point arithmetic. These equal-maximizer and additive formulas underlie the worked calculations in MIT 18.05, Reading 10b, section 3.1.
For the ordered sample of eight successes and two failures in likelihood function, on ,The score equation gives , hence . The negative second derivative proves strict concavity, so this is the unique interior maximum. Both counts are positive, so , while inside: the same point is the unique global maximum on . Counting only successes adds to the log-likelihood, leaving both derivatives and the MLE unchanged. For all-success or all-failure samples, the boundary analysis in maximum-likelihood estimator applies instead of an interior score equation.
The two panels below compare successes out of ten Bernoulli trials. Their peaks are at . The left panel uses relative height; the right panel uses the log-likelihood difference from each peak. These are the same comparison on two scales:A difference of means relative height , and a difference of means ; the log-likelihood scale makes small relative heights easier to see. Neither vertical axis is a parameter probability density function. The zero likelihood endpoints have log-likelihood and are outside the finite vertical range in the right panel.
Ten Bernoulli trials: relative likelihood heights and log-likelihood differences share the same peaks
. Details. Multiplying a likelihood function by a positive parameter-independent constant adds a constant to its log-likelihood. Subtracting its peak removes that constant. This is why the ordered-data and count-data curves coincide in this figure after rescaling. When differentiable, the gradient of the log-likelihood is the score function; the negative Hessian matrix is the observed information. A solution of a score equation still needs checking against other stationary points and boundaries: maximizing the log-likelihood does not automatically make it concave.
Machine epsilon Created 2026-10-14 Updated 2026-10-20
Here machine epsilon means the gap from one to the next larger value in normalized floating-point arithmetic:It is a relative resolution scale near one, not the smallest positive representable value and not a fixed absolute error for all magnitudes. In binary64, giveswhere is unit roundoff for rounding to nearest. Some authors instead call their machine epsilon; MIT 18.335J uses this half-gap convention. Always check which definition an error bound uses.[ref]
https://ocw.mit.edu/courses/18-335j-introduction-to-numerical-methods-spring-2019/2f313023ae3404bc217a81a31b227170_MIT18_335JS19_lec2.pdf. Persson, MIT 18.335J, Lecture 2, slides 3, 8–9: the half-gap convention
The gap below one is smaller: the preceding binary64 value is , whereas the next value above one is . Under nearest-even rounding,
1.0 + 2.0**-53 is exactly 1.0: the exact sum is a tie and one has the even final binary digit. By contrast, 1.0 + 2.0**-52 is the next value. Thus searching for the smallest increment that changes one by trial addition also depends on the rounding convention. At the next larger binary64 value is , illustrating why a small absolute increment can disappear at large magnitude. Matrix-chain cost model 2026-10-18
For matrix dimensions and , ordinary matrix multiplication computes matrix entries, each using scalar multiplications. Thus its cost is scalar multiplications, with additions if each sum starts from its first term. Here we minimize only the scalar multiplication count, using this dense matrix multiplication rule throughout. The counts describe arithmetic operations, rather than measured elapsed time; matrix multiplication methods that exploit structure or use faster formulas require a different cost rule.
Take matrices , , with matrix dimensions , , . Both groupings produce a matrix product, but their intermediate matrix dimensions differ:The second grouping first compresses into a matrix, avoiding the intermediate matrix . The saving is scalar multiplications, although both groupings use exactly two matrix multiplications. This is why counting only matrix multiplication operations hides the interesting choice.
The same matrix product can require 3840 or 780 scalar multiplications
. Original binary trees for the three-matrix example. Leaves keep in the same order. Each internal node gives its resulting matrix dimensions and the local scalar multiplication cost; adding those costs gives the total. Details.Associativity permits these regroupings in exact arithmetic; commutativity is neither assumed nor generally true for matrix multiplication. Swapping and here would even make their matrix product undefined. In floating-point arithmetic, round-off error can make the two groupings yield different computed matrix entries; the cost optimum alone does not guarantee the smallest numerical error.
NaN 2026-10-25
Node order in Newton interpolation 2026-10-18
Reordering the interpolation nodes changes the successive subsets used for the divided differences and the factors of the Newton polynomial. The final interpolation polynomial remains unchanged in exact arithmetic. For , reversing gives and values . The successive divided difference columns are nowFor example, the first second divided difference is . The top row becomes , givingThe earlier partial interpolants differ because they fit different subsets: fits , whereas fits . The highest divided difference is invariant because both complete top rows finish with the same set of four interpolation nodes; this is symmetry of divided differences.
Reversing the interpolation nodes changes the Newton construction but gives the same final polynomial
. Details. This distinction is useful when checking a divided difference table: permuting all the interpolation nodes must preserve its final divided difference, even though the intermediate entries change. It also explains why data can be appended in their arrival order. In floating-point arithmetic, the subtractions and divisions may accumulate different rounding errors in different orders; exact invariance describes the mathematical polynomial, rather than guaranteeing bit-for-bit equality of numerical results.
Number-theoretic transform 2026-10-20
A number-theoretic transform is a discrete Fourier transform computed in modular arithmetic. In a finite field with elements, choose a primitive root of unity of order dividing . The transform above is inverted using and . With sufficient zero padding, it computes polynomial products exactly modulo , avoiding floating-point arithmetic rounding.
Outward rounding 2026-10-14
Outward rounding replaces an exact lower endpoint by a representable value no larger than it, and an exact upper endpoint by a representable value no smaller than it. This preserves an interval enclosure under floating-point arithmetic. In the binary numeral system, most rational numbers cannot be represented exactly with finitely many digits, so the rounding direction is essential even for elementary calculations. Rump explains directed rounding and its use in interval bounds in §§4 and 5.3 of his survey.[ref]
https://www.tuhh.de/ti3/paper/rump/Ru10.pdf. Siegfried M. Rump, Verification methods: rigorous results using floating-point arithmetic, Acta Numerica 19, 287–449, 2010, §§4 and 5.3
To see the issue without long binary digit strings, use an illustrative decimal grid with step . Exact interval division gives . Rounding both endpoints to the nearest grid value gives , which excludes the true answer because . Outward rounding instead givesThis decimal toy illustrates the rule; its displayed endpoints are not the results of binary directed rounding. Real implementations need valid outward rounding throughout the calculation, including input conversion and intermediate interval arithmetic operations; rounding only the final output cannot repair an earlier lost bound. INTLAB's tutorial demonstrates why decimal input strings and previously rounded intermediate values need care.[ref]
https://www.tuhh.de/ti3/rump/intlab/demos/html/dintval.html. Rump, Interval computations in INTLAB, How to define an interval II and Invoking interval operations
Outward rounding encloses one third on a decimal toy grid; sign-changing interval products require all four endpoint combinations
. Above: rounding to the nearest decimal grid point misses , while down to and up to enclose it. Below: the Cartesian product of and has endpoint products , giving . The two same-side endpoint products alone give the invalid enclosure . Details. Pairing function Created 2026-10-03 Updated 2026-10-14
A pairing function is a computable function that gives a bijection from the Cartesian product to , with two computable functions recovering its coordinates. Here consists of the natural numbers, including zero. If is the pairing function and its decoding functions, the requirements areEvery ordered pair has exactly one code, every code represents an ordered pair, and decoding always terminates. For a bijection given by a total computable function, computability of the inverse function also follows by enumerating all ordered pairs until the one with code appears. A primitive recursive pairing function makes the stronger requirement that both encoding and coordinate decoding are primitive recursive.
The Cantor pairing function makes this concrete through triangular numbers:On the diagonal , list . There are ordered pairs there, and ordered pairs on earlier diagonals. Their codes therefore occupy precisely the consecutive natural numbers from through . These intervals touch without overlapping and cover all natural numbers; within each interval the offset determines the ordered pair. This proves both injectivity and surjectivity, hence the bijection. It also explains why the infinite grid is a countably infinite set: every ordered pair is reached after finitely many steps. A row-by-row listing would never finish its first infinite row. Authored treatments give the same diagonal construction with the coordinates exchanged.[ref]
https://www.cs.cmu.edu/~cdm/resources/02-coding.pdf. Klaus Sutner, Primitive Recursion, Carnegie Mellon University, spring 2021, slides 9–13: pairing systems and the Cantor polynomial
For example, the Cantor pairing function givesThe order of the coordinates matters: and are different ordered pairs with different codes.
The Cantor pairing function on a finite window: labels are codes, and the first 21 ordered pairs fill diagonals zero through five
. Details. To decode a natural number , find the unique diagonal index satisfyingThe inequality gives , so both recovered coordinates are natural numbers. At , , hence , , and . At , and both coordinates are zero. Solving the quadratic inequality gives the equivalent floor function expressionThis is exact as a statement about the real numbers and their square roots. An implementation using floating-point arithmetic can round across a diagonal boundary, especially for large . Use an exact integer square root instead: with computed using integer arithmetic, . Alternatively, search for the diagonal using exact integer comparisons. The primitive recursive pairing function proof below uses bounded minimization and needs no approximate square root.
A pairing function is a reversible encoding: unlike a hash function mapping arbitrarily many inputs into a fixed finite range, it loses no coordinates. This works because the mathematical natural numbers have no upper bound. A machine word with binary digits has possible values, while two such words have possible ordered pairs; a bijection into one word of the same width is impossible. Evaluating the Cantor pairing function in a fixed-width integer type can overflow, including in the intermediate product . Exact implementation requires sufficiently large integer storage or an explicit restricted input range. One mathematical code need not occupy fewer binary digits than its two inputs.
Iterating a pairing function gives a reversible encoding of tuples of any fixed positive length. With the left-nesting convention, the Cantor pairing function encodes asDecode the outer ordered pair first: gives . Decode its first coordinate to recover , giving the nested ordered pair and thus the original tuple .
The tuple length and nesting convention must be known. The same code represents as a two-entry tuple and as a three-entry tuple; nesting alone does not make variable-length tuples self-describing. To encode variable-length tuples, supply their length or another explicit termination convention as part of the encoding. This simple change of representation is useful in computability theory and Gödel numbering: a function of several natural numbers can be studied through a single numerical input, while all coordinates remain recoverable. The striking fact is that a whole infinite grid can be serialized without omitting a point.
A historical reference for comparing sets through bijections is Georg Cantor's paper Ein Beitrag zur Mannigfaltigkeitslehre, published in 1878 in volume 84 of Journal für die reine und angewandte Mathematik, pages 242–258.[ref]
https://doi.org/10.1515/crelle-1878-18788413. Georg Cantor, Ein Beitrag zur Mannigfaltigkeitslehre, 1878: publisher bibliographic record
Three advantages of integer arithmetic for raster graphics are:
- Cheap, fast operations. Historically, integer addition, subtraction and shifts needed much less hardware and execution time than floating-point arithmetic, especially on machines without a floating-point unit. An incremental Bresenham's line algorithm needs only a few additions and a decision per pixel.
- Exact decisions. Provided integer overflow is excluded, the scaled midpoint line decision is exact. There is no accumulated rounding error that can move a decision across a half-pixel boundary; equality has a reproducible tie rule.
- Simple storage and hardware. Integer coordinates already identify pixels. An implementation can keep coordinates and decision variables in ordinary registers and use a small add/compare datapath, avoiding conversion between floating-point numbers and integer screen addresses.
Let the oriented vertices be , in an order such that points out of the front face. The given nondegeneracy guarantees . A ray with nonzero direction approaches the front face only ifReject . This combines back-face culling with rejection of parallel rays, including the coplanar case for this ordinary surface-hit test. The ray-plane intersection parameter isReject ; for rays launched from existing surfaces use a positive lower cutoff to avoid counting the launch surface. Form .
Finally determine whether lies inside the triangle. For , , , computeThese solve . The barycentric coordinates are , so the complete acceptance criterion isThe inequalities include the edges and vertices. A renderer sharing edges between triangles should use a consistent numerical edge convention; small floating-point arithmetic errors near a shared boundary should not create cracks. Normalizing is unnecessary for this intersection calculation because its scale cancels.
At each primary hit , send a shadow ray toward each point light. An especially clear parameterization isIf an opaque scene surface intersects this open segment, the source is hidden. The finite interval is essential: an object beyond the light must not cast a shadow at . Exclude the launch surface with a small geometrically appropriate origin offset or positive minimum parameter, so floating-point arithmetic does not create a false self-intersection.
Introduce a visibility factor equal to zero when blocked and one otherwise. The modified equation isA blocked light loses both its diffuse and specular contributions. The simple ambient approximation remains. Opaque point lights produce hard shadow boundaries. Use a consistent sidedness policy for occluders: an opaque closed solid blocks from either crossing side, so a two-sided blocker test is appropriate even when primary visibility uses back-face culling. An any-hit query can stop as soon as it finds one blocker before the light.
The tight axis-aligned bounding box is . Bisect vertically at , giving a right child . For a scalar implicit function representing the same constructive solid geometry solid, useWith the convention inside, set intersection corresponds to the maximum, and set union to the minimum. These operations encode membership; is not a signed distance function.
Since every is an affine function, its extreme values on occur at corners. Exact real-arithmetic interval arithmetic gives:
| Function | Range on | , propagated | , propagated |
|---|
Each leaf range is exact, but combining independent intervals forgets that the expressions share . The final enclosure need not be the exact range of . For example, equality would require both , hence , and , hence on , which is impossible. The enclosure is still sufficient for a reliable three-way decision:Here the result is unresolved. This is a real mixed box, rather than only a pessimistic test: is strictly inside, whereas is outside. A zero endpoint alone can also mean contact with the boundary, so equality must not be treated as proof of strict interior or strict exterior. In floating-point arithmetic, certified bounds require outward rounding.
Continue splitting unresolved boxes, normally alternating axes or splitting the longest side. Propagate the interval arithmetic results through the constructive solid geometry tree, discard exterior boxes and stop refining strict interior boxes. In sufficiently small boundary boxes, locate crossings of the active implicit equations with box edges and connect them into boundary line segments. Retain corners and resolve ambiguous multiple crossings by further refinement; here every genuine boundary piece is straight, so its supporting implicit equation allows exact intersection rather than a curved approximation. A maximum boundary-box diagonal gives spatial localization at that scale, provided no boundary components are discarded; corner-sign sampling alone provides no such guarantee.
The tight box saves empty-space work, but it is awkward for extracting facets. Entire boundary line segments, notably , and , lie on the initial box boundary, and lies on the first splitting straight line. A sign-change-only method may have no exterior sample on the other side and lose such pieces; exact zeros also persist through refinement. A slightly padded initial axis-aligned bounding box, together with an explicit rule for boundary-coincident pieces, makes the faceting more robust. The tight box is therefore economical for enclosure but not the best unqualified choice for a simple faceting implementation.
For each sample, include both its marker and its bar. A bar's lower vertical limit is , including negative bars below the horizontal axis. Its horizontal half-width is , rather than . Its marker extends by in both directions. Therefore that sample's axis-aligned bounding box isTaking successive bounding unions includes every sample. Finally unite with to include the stipulated axes. The printed upper-corner formula has one extra closing parenthesis; both the lower-corner formula and the picture confirm the coordinatewise interpretation used here.[ref]
The following commented Java object method may be placed in a graph-view utility software class. It uses
Rect from part (a) and one iterator snapshot from part (e).static Rect barBounds(DataList data, double C, double M) {
if (!Double.isFinite(C) || !Double.isFinite(M) || C <= 0 || M <= 0)
throw new IllegalArgumentException("positive finite margins required");
List<Point> p = new ArrayList<Point>();
for (Point point : data) p.add(point);
int n = p.size();
if (n < 2) throw new IllegalArgumentException("at least two points required");
// This central square supplies the required minimum axis extents.
Rect bounds = new Rect(new Point(-M, -M), new Point(M, M));
for (int i = 0; i < n; ++i) {
double x = p.get(i).getX(), y = p.get(i).getY();
double width;
if (i == 0) {
width = p.get(1).getX() - x;
} else if (i == n - 1) {
width = x - p.get(i - 1).getX();
} else {
width = Math.min(x - p.get(i - 1).getX(),
p.get(i + 1).getX() - x);
}
// Include whichever is wider: marker or half of the bar.
double half = Math.max(C, width / 2.0);
// The bar reaches the baseline; the marker reaches y +/- C.
Rect item = new Rect(new Point(x - half, Math.min(0.0, y - C)),
new Point(x + half, Math.max(0.0, y + C)));
bounds = bounds.Union(item);
}
return bounds;
}This uses the usual assumption that coordinate differences and expanded bounds are representable as finite
double values. Rect rejects overflowed bounds; numerical range extension is not part of the requested geometry. As with all floating-point arithmetic, the calculation approximates the corresponding exact real number formulas.The expression is the Binet formula for the Fibonacci numbers. Compute the two roots and round the result to the nearest integer:
from math import sqrt
def binet(n):
phi = (1 + sqrt(5)) / 2
psi = (1 - sqrt(5)) / 2
return round((phi**n - psi**n) / sqrt(5))Represent the zero polynomial by ThusThe sentinel is a representation convention, not an assertion that the mathematical degree of the zero polynomial is an ordinary integer. In parts (b)–(e), algebraic correctness uses exact arithmetic on real numbers; ordinary floating-point arithmetic introduces rounding and needs an additional numerical policy if exact zero tests are to be replaced.
degree = -1, with an allocated one-element array whose element is zero. Its coefficient prefix is empty; the spare cell is merely convenient storage. For every nonzero polynomial, require degree >= 0, sufficient allocated capacity, and a nonzero leading polynomial coefficient.PROCEDURE Zero(VAR p: Poly);
BEGIN
p.degree := -1; NEW(p.coeff, 1); p.coeff[0] := 0.0
END Zero;
PROCEDURE Normalize(VAR p: Poly);
BEGIN
WHILE p.degree >= 0 DO
IF p.coeff[p.degree] # 0.0 THEN RETURN END;
DEC(p.degree)
END
END Normalize;For The first is a discrete uniform distribution; the second is a Bernoulli distribution on Boolean values. Their exact mathematical probability mass functions areEach support contains exactly the positive-probability outcomes once, and the probabilities sum to one.
Uniform, require a nonempty integer interval. Compute its size in Long before converting to Double, avoiding integer overflow in u-l+1. For Flip, require , and omit zero-probability outcomes from the reported support.class Uniform(l: Int, u: Int) extends FiniteDist[Int] {
require(l <= u)
private val size = u.toLong - l.toLong + 1L
def getDom: List[Int] = {
val result = List.newBuilder[Int]
var x = l.toLong
while (x <= u.toLong) { result += x.toInt; x += 1L }
result.result()
}
def getProb(x: Int): Double =
if (l <= x && x <= u) 1.0 / size.toDouble else 0.0
}
class Flip(p: Double) extends FiniteDist[Boolean] {
require(0.0 <= p && p <= 1.0)
def getDom: List[Boolean] =
if (p == 0.0) List(false)
else if (p == 1.0) List(true)
else List(true, false)
def getProb(x: Boolean): Double = if (x) p else 1.0-p
}Double approximates these exact values by floating-point arithmetic. Materializing a huge support is limited by available memory; the Long calculation keeps its cardinality and endpoints arithmetically correct.







