Documentation home / Native modules / gs_compute
gs_compute: Complete API and Usage
A native C numerical toolkit for financial calculations, descriptive statistics, vectors, matrix algebra, linear systems, numerical integration and differentiation, unit conversion, numeric comparisons, benchmarking, and reproducible random sampling. This reference follows the module's exported functions and validation logic.
82 exported functions Native C CPU IEEE-754 double Module ABI v1
Import the module once with import gs_compute;, then call its functions through the module object. The module does not add language keywords or change the VM.
Contents
- Build, install and import
- GSVE language usage
- Financial and percentage APIs
- Scalar and numeric helpers
- Statistics APIs
- Vector APIs
- Matrix APIs
- Numerical methods
- NumPy-inspired array APIs
- Unit conversion
- Validation and benchmarking
- Seeded random APIs
- Types, limits and null results
- Complete application example
1. Build, install and import
gs_compute is implemented in C as a native shared-library module. Build it using the gs_compute build workflow in the greenServeFE build repository, then place gs_compute.so in a directory searched by the native module loader.
# Example installation location
/usr/local/lib/modules/gs_compute.so
# Make the module directory visible to the process
export GREENSERVE_MODULE_PATH=/usr/local/lib/modules
export LD_LIBRARY_PATH=/usr/local/lib/modules:$LD_LIBRARY_PATH
Run a GSVE file after the module is installed:
import gs_compute;
print(gs_compute.info());
print(gs_compute.percent(250, 12));
gs_compute.so at runtime.2. GSVE language usage
Examples use the actual greenServeFE language forms: define for variable declarations, func for functions, semicolons for statements, arrays with square brackets, and object values with braces. Module functions are called with dot-member access.
import gs_compute;
define values = [12, 18, 24, 30];
define summary = gs_compute.stats(values);
print(summary.mean);
print(summary.median);
print(summary.stddev);
func price_after_discount(price, rate) {
return gs_compute.discount(price, rate);
}
print(price_after_discount(120, 15));
All numeric arguments must be GSVE numbers. Numeric strings are not automatically parsed by this module. Convert text deliberately with the language's numeric conversion facilities before calling a numerical API.
3. Financial and percentage APIs
percent(value, percentage)
Returns value * percentage / 100. The percentage may be negative or greater than 100; both inputs must be finite numbers.
print(gs_compute.percent(250, 12)); # 30percent_change(before, after)
Returns the signed percentage change: (after - before) / abs(before) * 100. Returns null when before is zero.
print(gs_compute.percent_change(80, 100)); # 25
print(gs_compute.percent_change(100, 80)); # -20discount(price, percentage)
Returns the price after applying a discount. Requires price >= 0 and 0 <= percentage <= 100.
define sale_price = gs_compute.discount(250, 20);
print(sale_price); # 200tax(price, percentage)
Returns price including the percentage tax: price * (1 + percentage / 100). Requires a non-negative price and percentage.
print(gs_compute.tax(200, 5)); # 210tip(bill, percentage, people?)
Calculates a tip and split. people defaults to 1 and, when supplied, must be a positive integer. Returns an object with tip, total, and per_person.
define split = gs_compute.tip(120, 15, 4);
print(split.tip); # 18
print(split.total); # 138
print(split.per_person); # 34.5compound(principal, annual_rate_percent, years)
Calculates compound growth with annual compounding. The four-argument overload compound(principal, annual_rate_percent, periods_per_year, years) selects the compounding frequency. Principal must be non-negative; rate must be greater than -100%; periods must be a positive integer; years must be between 0 and 100000.
define annual = gs_compute.compound(1000, 5, 3);
define monthly = gs_compute.compound(1000, 5, 12, 3);
print(annual);
print(monthly);loan_payment(principal, annual_rate_percent, months)
Returns the fixed monthly payment for a fully amortizing loan. Months must be a positive integer (maximum 120000); principal and annual rate must be non-negative. A zero interest rate returns principal / months.
define payment = gs_compute.loan_payment(12000, 6, 24);
print(payment);4. Scalar and numeric helpers
clamp(value, lower, upper)
Constrains a number to the inclusive bounds. If lower is greater than upper, the implementation swaps the bounds.
print(gs_compute.clamp(125, 0, 100)); # 100lerp(start, end, t)
Linear interpolation or extrapolation: start + (end - start) * t. Values of t outside 0–1 extrapolate.
print(gs_compute.lerp(10, 20, 0.25)); # 12.5map_range(value, input_min, input_max, output_min, output_max)
Maps a value linearly from one range to another. The input range endpoints must differ; the value is not clamped to the input range.
print(gs_compute.map_range(5, 0, 10, 0, 100)); # 50sum(numbers)
Returns the sum of a non-empty or empty numeric array (an empty array sums to zero). Every element must be a finite number; the array limit for this function is 1,000,000 values.
print(gs_compute.sum([10, 20, 30])); # 60quadratic(a, b, c)
Solves a*x*x + b*x + c = 0 for real roots. Returns a two-element array in minus-root then plus-root order. Returns null if a is zero or the discriminant is negative.
define roots = gs_compute.quadratic(1, -5, 6);
print(roots[0]); # 2
print(roots[1]); # 35. Statistics APIs
stats(numbers)
Returns a descriptive-statistics object: count, sum, mean, min, max, median, range, variance, and stddev. Variance is population variance (divisor N), and standard deviation is its square root. Median sorts a copy of the input values.
define s = gs_compute.stats([2, 4, 4, 4, 5, 5, 7, 9]);
print(s.count); # 8
print(s.mean); # 5
print(s.median); # 4.5
print(s.variance); # 4
print(s.stddev);mean(numbers)
Returns the arithmetic mean using an incremental mean update. Requires at least one finite numeric value.
print(gs_compute.mean([2, 4, 6, 8])); # 5variance(numbers)
Returns population variance using Welford's online update. Requires at least one finite numeric value.
print(gs_compute.variance([2, 4, 6, 8]));6. Vector APIs
Vectors are one-dimensional GSVE arrays of finite numbers. Operations that combine two vectors require equal lengths.
dot(vector_a, vector_b)
Returns the dot product, the sum of pairwise products. Both vectors must have the same non-zero length.
print(gs_compute.dot([1, 2, 3], [4, 5, 6])); # 32vector_add(vector_a, vector_b)
Returns element-wise addition of two equally sized vectors.
print(gs_compute.vector_add([1, 2], [10, 20])); # [11, 22]vector_sub(vector_a, vector_b)
Returns element-wise subtraction a - b.
print(gs_compute.vector_sub([10, 20], [1, 2])); # [9, 18]vector_scale(vector, scalar)
Multiplies every vector element by a finite scalar.
print(gs_compute.vector_scale([1, 2, 3], 2)); # [2, 4, 6]norm(vector)
Returns the Euclidean (L2) norm. Uses a scaled sum-of-squares algorithm to reduce overflow and underflow risk. The vector must be non-empty.
print(gs_compute.norm([3, 4])); # 57. Matrix APIs
Matrices are rectangular arrays of equally sized row arrays. Every cell must be a finite number. Matrix operations reject ragged rows and incompatible dimensions.
matrix_add(matrix_a, matrix_b) and matrix_sub(matrix_a, matrix_b)
Element-wise addition or subtraction. Both matrices must have identical row and column counts.
define a = [[1, 2], [3, 4]];
define b = [[5, 6], [7, 8]];
print(gs_compute.matrix_add(a, b));
print(gs_compute.matrix_sub(b, a));transpose(matrix)
Returns a new matrix with rows and columns exchanged. Rectangular matrices are supported.
print(gs_compute.transpose([[1, 2, 3], [4, 5, 6]]));
# [[1, 4], [2, 5], [3, 6]]matmul(matrix_a, matrix_b)
Performs matrix multiplication. If A has shape r × k, B must have shape k × c, and the result has shape r × c. The C implementation uses cache-friendly blocked multiplication.
define product = gs_compute.matmul(
[[1, 2], [3, 4]],
[[5, 6], [7, 8]]
);
print(product); # [[19, 22], [43, 50]]matrix_vector(matrix, vector)
Multiplies an r × c matrix by a vector of length c; returns a vector of length r.
print(gs_compute.matrix_vector([[1, 2], [3, 4]], [5, 6]));
# [17, 39]matrix_determinant(matrix)
Computes the determinant of a square matrix using Gaussian elimination with partial pivoting. A singular matrix returns numeric zero; malformed or non-square input returns null.
print(gs_compute.matrix_determinant([[1, 2], [3, 4]])); # -2matrix_inverse(matrix)
Computes the inverse of a square non-singular matrix using Gauss–Jordan elimination with scaled partial pivoting. Singular or numerically rejected matrices return null.
define inverse = gs_compute.matrix_inverse([[4, 7], [2, 6]]);
print(inverse);zeros(rows, columns)
Creates a matrix of the requested positive integer dimensions, filled with zeros.
print(gs_compute.zeros(2, 3)); # [[0, 0, 0], [0, 0, 0]]identity(size)
Creates a square identity matrix of the requested positive integer size. The current implementation accepts sizes up to 3162.
print(gs_compute.identity(3));
# [[1, 0, 0], [0, 1, 0], [0, 0, 1]]solve(matrix_a, vector_b)
Solves the square linear system A*x = b using Gaussian elimination with scaled partial pivoting. The vector length must equal the matrix dimension. Singular or numerically unstable systems return null.
define solution = gs_compute.solve(
[[2, 1], [1, 3]],
[8, 13]
);
print(solution); # [2.2, 3.6]8. Numerical methods
integrate(x_values, y_values)
Approximates the definite integral for sampled data using the composite trapezoidal rule. The two arrays must have equal length of at least two. X values must be non-decreasing; repeated x values contribute zero width.
define area = gs_compute.integrate(
[0, 1, 2, 3],
[0, 1, 2, 3]
);
print(area); # 4.5differentiate(x_values, y_values)
Returns a derivative estimate at every sample. It uses forward difference at the first point, backward difference at the last point, and a two-point central difference for interior points. X coordinates must be strictly increasing wherever a stencil is evaluated; duplicate or decreasing coordinates return null.
define slope = gs_compute.differentiate(
[0, 1, 2, 3],
[0, 1, 4, 9]
);
print(slope);linspace(start, end, count)
Creates count evenly spaced numbers including both endpoints when count is greater than one. When count is one, the result contains only start. Count must be a positive integer.
print(gs_compute.linspace(0, 1, 5)); # [0, 0.25, 0.5, 0.75, 1]9. NumPy-inspired array APIs
The 1.0.2 native implementation adds a compact array-computing layer. It works with ordinary GSVE arrays and rectangular nested arrays; it does not introduce a new array type, syntax, opcode, or VM feature. The VM still compiles GSVE source to bytecode and invokes these functions through the existing native-module ABI.
Array construction and shape
shape(array)
Returns [length] for a vector or [rows, columns] for a rectangular matrix. Ragged nested arrays are rejected.
print(gs_compute.shape([2, 4, 6])); # [3]
print(gs_compute.shape([[1, 2], [3, 4]])); # [2, 2]flatten(array_or_matrix)
Returns a one-dimensional numeric array. A matrix is flattened in row-major order; a vector is returned as a copied numeric array.
print(gs_compute.flatten([[1, 2], [3, 4]])); # [1, 2, 3, 4]reshape(vector, rows, columns)
Reshapes a flat numeric array into a rectangular matrix. The requested positive integer dimensions must multiply to the input element count.
print(gs_compute.reshape([1, 2, 3, 4, 5, 6], 2, 3));full(rows, columns, fill_value), ones(rows, columns)
Create a matrix of the requested positive integer dimensions, filled with the supplied value or with ones.
print(gs_compute.full(2, 3, 7));
print(gs_compute.ones(2, 2));arange(stop), arange(start, stop), arange(start, stop, step)
Creates a vector beginning at start (zero by default), advancing by step (one by default), and stopping before stop. A zero step, more than three arguments, or an excessive allocation returns null. The result may be empty when the step points away from the stop value.
print(gs_compute.arange(5)); # [0, 1, 2, 3, 4]
print(gs_compute.arange(2, 9, 2)); # [2, 4, 6, 8]Unary element-wise functions
Each function takes one numeric vector and returns a new vector with the operation applied element by element. Domain errors and non-finite results are rejected by the numeric-array result builder.
| Function | Operation | Example |
|---|---|---|
abs(values) | Absolute value | gs_compute.abs([-2, 3]) |
sqrt(values) | Square root; negative inputs are invalid | gs_compute.sqrt([4, 9]) |
exp(values) | Natural exponential, eˣ | gs_compute.exp([0, 1]) |
log(values), log10(values) | Natural and base-10 logarithms; inputs must be positive | gs_compute.log10([1, 10, 100]) |
sin(values), cos(values), tan(values) | Trigonometric functions; angles are in radians | gs_compute.sin([0, 1.57079632679]) |
floor(values), ceil(values) | Round toward negative or positive infinity | gs_compute.floor([1.8, -1.2]) |
round(values) | Round to the nearest integer using the C nearbyint behavior and active floating-point rounding mode | gs_compute.round([1.4, 1.6]) |
negative(values) | Negate each element | gs_compute.negative([2, -3]) |
Binary element-wise functions
These functions accept scalar/scalar arguments (returning a scalar), scalar/array or array/scalar arguments (returning an array), or two equal-length arrays (returning an array). Two arrays of different lengths are rejected.
| Function | Operation | Example |
|---|---|---|
add(a, b) | Addition | gs_compute.add([1, 2], 10) |
subtract(a, b) | Subtraction, a − b | gs_compute.subtract([5, 8], [1, 3]) |
multiply(a, b) | Multiplication | gs_compute.multiply([2, 3], 4) |
divide(a, b) | Division; zero divisors are invalid | gs_compute.divide([8, 9], 3) |
power(a, b) | Exponentiation, aᵇ | gs_compute.power([2, 3], 2) |
maximum(a, b), minimum(a, b) | Element-wise maximum or minimum | gs_compute.maximum([1, 8], [4, 5]) |
Reductions, ordering and clipping
cumsum(values)
Returns cumulative sums in input order. For example, [1, 2, 3] becomes [1, 3, 6].
print(gs_compute.cumsum([1, 2, 3, 4]));product(values), prod(values)
Returns the product of all elements. prod is an alias of product; the empty product is 1.
print(gs_compute.product([2, 3, 4]));std(values)
Returns population standard deviation, using Welford-style online accumulation. Requires a non-empty numeric array. This is equivalent to the square root of population variance.
print(gs_compute.std([2, 4, 6, 8]));sort(values)
Returns a new array sorted in ascending numeric order; the input array is not modified.
print(gs_compute.sort([9, 2, 7, 1]));clip(values, lower, upper)
Returns a copy with every element constrained to the inclusive interval. The lower bound must not exceed the upper bound.
print(gs_compute.clip([-5, 5, 15], 0, 10)); # [0, 5, 10]array_max(values), array_min(values)
Return the largest or smallest element in a non-empty numeric array.
print(gs_compute.array_max([3, 8, 2]));
print(gs_compute.array_min([3, 8, 2]));argmax(values), argmin(values)
Return the zero-based index of the first occurrence of the largest or smallest value in a non-empty numeric array.
print(gs_compute.argmax([3, 8, 8, 2])); # 1
print(gs_compute.argmin([3, 8, 2])); # 2Additional matrix helpers and compatibility aliases
matrix_trace(matrix)
Returns the sum of the main diagonal. Requires a square matrix.
print(gs_compute.matrix_trace([[1, 2], [3, 4]])); # 5matrix_scale(matrix, scalar)
Multiplies every matrix element by a scalar and returns a new matrix.
print(gs_compute.matrix_scale([[1, 2], [3, 4]], 0.5));diag(vector_or_matrix)
For a vector, creates a square diagonal matrix. For a matrix, extracts its main diagonal as a vector. Matrix extraction supports rectangular matrices and returns the shorter diagonal length.
print(gs_compute.diag([2, 3, 4]));
print(gs_compute.diag([[1, 2], [3, 4]])); # [1, 4]eye(size)
Alias of identity(size); creates a square identity matrix.
print(gs_compute.eye(3));Aliases: matrix_multiply(a, b) calls the same implementation as matmul(a, b); prod(values) aliases product(values); and var(values) aliases variance(values). These names are separately exported and are case-sensitive.
10. Unit conversion
convert(value, from_unit, to_unit)
Converts a number between supported units in the same dimension. Unit strings are case-sensitive. Identical unit strings return the input value.
| Dimension | Supported units |
|---|---|
| Length | m, km, cm, mm, mi, ft, in, yd |
| Mass | kg, g, mg, lb, oz |
| Time | s, ms, min, h, day |
| Decimal data size | B, KB, MB, GB (base 1000) |
| Binary data size | KiB, MiB, GiB (base 1024) |
| Temperature | C, F, K |
print(gs_compute.convert(5, "km", "m")); # 5000
print(gs_compute.convert(32, "F", "C")); # 0
print(gs_compute.convert(1, "GiB", "MB")); # 1073.741824
Temperature conversions use Celsius as the intermediate scale. Kelvin values below absolute zero are rejected. Unsupported units and cross-dimension conversions return null.
11. Validation and benchmarking
is_close(a, b, absolute_tolerance?, relative_tolerance?)
Returns a boolean indicating whether abs(a-b) <= abs_tol + rel_tol * max(abs(a), abs(b)). Both tolerances default to 1e-9 and must be non-negative.
print(gs_compute.is_close(0.1 + 0.2, 0.3));
print(gs_compute.is_close(1000, 1000.1, 0.001, 0.0002));is_null(value)
Returns true only when the first supplied argument is the VM's null value. If no argument is supplied, returns false.
define result = gs_compute.matrix_inverse([[1, 2], [2, 4]]);
print(gs_compute.is_null(result));benchmark_stats(count)
Runs a fixed internal workload: generates values cycling from 0 through 999, computes Welford mean and variance, sorts the generated values, and measures CPU time. Returns an object containing count, elapsed_ms, mean, variance, min, max, median, and workload. Count must be an integer from 1 through 10,000,000.
define result = gs_compute.benchmark_stats(100000);
print(result.count);
print(result.elapsed_ms);
print(result.workload);This benchmarks the module's fixed statistics workload, not arbitrary user functions or the entire VM. Timings vary by CPU, system load and compiler build.
12. Seeded random APIs
random_seed(seed)
Sets the module's deterministic pseudo-random generator state and returns true on success. The seed must be a finite number with absolute value no greater than 9007199254740991. A zero seed is mapped to the generator's non-zero default state.
print(gs_compute.random_seed(12345));random(minimum?, maximum?)
Returns a pseudo-random floating-point value in the half-open interval from the lower bound up to (but not including) the upper bound. Defaults are 0 and 1. If bounds are reversed, they are swapped.
gs_compute.random_seed(7);
print(gs_compute.random()); # [0, 1)
print(gs_compute.random(10, 20)); # [10, 20)random_array(count, minimum?, maximum?)
Returns an array of pseudo-random floating-point values. Count must be an integer from 0 through 10,000,000. Bounds default to 0 and 1 and are swapped when supplied in reverse order.
gs_compute.random_seed(42);
define samples = gs_compute.random_array(5, -1, 1);
print(samples);13. Module metadata
info()
Returns metadata about the loaded module:
name:"gs_compute"version:"1.0.2"backend:"native C CPU"numeric_type:"IEEE-754 double"status: a capability summary string
define details = gs_compute.info();
print(details.name);
print(details.version);
print(details.backend);14. Types, limits and null results
- Numeric values: numerical parameters must be finite GSVE numbers. Numeric strings are not accepted as numbers.
- Arrays: vector and data-array functions require arrays containing only finite numbers. Matrix functions require non-empty rectangular nested arrays of finite numbers.
- Invalid input: most validation failures, unsupported units, incompatible dimensions, singular inverses/linear systems, non-finite calculations and allocation failures return the VM value
null.matrix_determinantis a special case: a valid singular square matrix returns numeric zero. - Statistics:
statsandsumcap the input at 1,000,000 values. Scientific array and matrix helpers use a 10,000,000-element guard, subject to shape-specific and memory checks. - Matrix creation:
zerosrequires positive integer dimensions and limits total cells to 10,000,000.identitycurrently accepts sizes up to 3162. - Precision: values use C
double/ IEEE-754 floating-point. Exact decimal equality is not guaranteed; useis_closefor approximate comparisons. - Randomness: the PRNG state is shared by calls to this module instance. Reseeding resets the sequence. It is not a cryptographic random source.
null, inspect argument types, array shape, dimensions, bounds and numeric finiteness. Use gs_compute.is_null(result) to test the returned value explicitly.15. Complete GSVE example: sales and scientific calculations
import gs_compute;
# Sales calculations
define unit_price = 89.50;
define quantity = 12;
define subtotal = unit_price * quantity;
define discount_amount = gs_compute.percent(subtotal, 10);
define discounted = gs_compute.discount(subtotal, 10);
define total = gs_compute.tax(discounted, 5);
print("Subtotal:");
print(subtotal);
print("Discount amount:");
print(discount_amount);
print("Total after discount and tax:");
print(total);
# Statistics for daily sales
define daily_sales = [120, 135, 98, 160, 145, 172, 155];
define report = gs_compute.stats(daily_sales);
print("Average daily sales:");
print(report.mean);
print("Median daily sales:");
print(report.median);
print("Population standard deviation:");
print(report.stddev);
# Vector and matrix calculations
define demand = [10, 15, 20];
define unit_cost = [3, 4, 5];
print("Weighted total:");
print(gs_compute.dot(demand, unit_cost));
define matrix_a = [[2, 1], [1, 3]];
define matrix_b = [[8, 1], [13, 2]];
print(gs_compute.matmul(matrix_a, matrix_b));
print(gs_compute.solve(matrix_a, [8, 13]));
print(gs_compute.matrix_inverse(matrix_a));
# Sampled numerical data
define x = [0, 1, 2, 3, 4];
define y = [0, 1, 4, 9, 16];
print("Approximate area:");
print(gs_compute.integrate(x, y));
print("Approximate derivative:");
print(gs_compute.differentiate(x, y));
# Reproducible experiment
gs_compute.random_seed(2026);
define samples = gs_compute.random_array(8, 0, 100);
print(samples);
print(gs_compute.stats(samples));
17. Complete exported API catalogue
The following catalogue is cross-checked against greenServeFE_module_init in the native gs_compute.c. These are the complete 82 exported members in version 1.0.2; names are case-sensitive and are called as gs_compute.name(...).
| Group | Exported API | Purpose / result |
|---|---|---|
| Metadata | info() | Module name, version, backend, numeric representation and capability status. |
| Finance | percent, percent_change, discount, tax, tip, compound, loan_payment | Percentage calculations, sale prices, tax, tips, compound growth and loan payments. |
| Scalar math | clamp, lerp, map_range, sum, quadratic, convert | Bounds, interpolation, range mapping, summation, quadratic roots and unit conversion. |
| Statistics | stats, mean, variance, var, std | Descriptive summary, arithmetic mean, population variance and standard deviation. |
| Vectors | dot, vector_add, vector_sub, vector_scale, norm | Dot product, vector arithmetic, scaling and Euclidean norm. |
| Matrices | matrix_add, matrix_sub, transpose, matmul, matrix_multiply, matrix_vector, matrix_determinant, matrix_inverse, zeros, identity, eye, solve, matrix_trace, matrix_scale, diag | Matrix arithmetic, multiplication, transforms, diagonal helpers, determinant, inverse and linear systems. |
| Numerical methods | integrate, differentiate, linspace | Trapezoidal integration, finite differences and evenly spaced samples. |
| Array construction | shape, flatten, reshape, full, ones, arange | Shape inspection, flattening, reshaping and array/matrix creation. |
| Unary array math | abs, sqrt, exp, log, log10, sin, cos, tan, floor, ceil, round, negative | Element-wise unary mathematical functions on numeric arrays. |
| Binary array math | add, subtract, multiply, divide, power, maximum, minimum | Scalar and element-wise binary operations with limited scalar-to-array broadcasting. |
| Array reductions | cumsum, product, prod, sort, clip, array_max, array_min, argmax, argmin | Cumulative sums, products, sorting, clipping, extrema and zero-based extrema indices. |
| Units | convert(value, from_unit, to_unit) | Length, mass, time, data-size and temperature conversion. |
| Validation / measurement | is_close, is_null, benchmark_stats | Tolerance-aware comparison, null testing and a native statistics benchmark. |
| Random sampling | random_seed, random, random_array | Repeatable pseudo-random scalar and array samples; not cryptographic randomness. |
There are 82 exported members, including separately exported aliases. compound accepts exactly three or four arguments: compound(principal, annual_rate_percent, years) or compound(principal, annual_rate_percent, periods_per_year, years). The NumPy-inspired API supports vectors and rectangular matrices, not arbitrary N-dimensional arrays.
18. Exact unit identifiers
convert(value, from_unit, to_unit) requires unit identifiers to be strings and matches them exactly, including capitalization. Conversions are permitted only within the same physical group, except temperature, which uses Celsius as its intermediate base.
| Group | Accepted identifiers |
|---|---|
| Length | m, km, cm, mm, mi, ft, in, yd |
| Mass | kg, g, mg, lb, oz |
| Time | s, ms, min, h, day |
| Data size (decimal) | B, KB, MB, GB (base 1000) |
| Data size (binary) | KiB, MiB, GiB (base 1024) |
| Temperature | C, F, K |
import gs_compute;
print(gs_compute.convert(5, "km", "m")); # 5000
print(gs_compute.convert(2, "lb", "kg"));
print(gs_compute.convert(90, "min", "h")); # 1.5
print(gs_compute.convert(1, "MiB", "B")); # 1048576
print(gs_compute.convert(32, "F", "C")); # 0
print(gs_compute.convert(0, "C", "K")); # 273.15
Unsupported identifiers, cross-group conversions (for example metres to kilograms), negative Kelvin input, or a result that is not finite return null. Identical supported strings return the original numeric value.
19. Argument, array and result semantics
- Numbers: numeric parameters must be GSVE number values, not numeric strings. The module rejects NaN and infinity for numeric arguments.
- Arrays: vector inputs are one-dimensional arrays of finite numbers. Matrix inputs are non-empty rectangular arrays whose rows are equally sized arrays of finite numbers.
- Dimensions: paired vectors must have equal lengths; paired element-wise matrices must have equal shapes; matrix multiplication requires the left column count to equal the right row count; matrix-vector multiplication requires vector length to equal matrix columns.
- Empty arrays:
sum([])returns0.stats([]),mean([]),variance([]),dot([], [])andnorm([])returnnull. - Null versus zero: a mathematically valid zero is returned as numeric zero.
nullsignals rejected input, unsupported conversion, singular/unstable solve or inverse, or a non-finite computed result. A singular determinant is the exception: it returns0. - Extra arguments: most functions check that the required arguments exist and validate the arguments they use; do not rely on extra arguments being rejected.
compoundis strict and accepts exactly three or four arguments.
20. Implementation limits and algorithm notes
| Area | Implementation rule |
|---|---|
| Statistics / sum | stats and sum accept at most 1,000,000 values. stats requires at least one value; sum accepts an empty array. |
| Scientific arrays / matrices | General scientific vector and matrix helpers enforce a 10,000,000-element guard, along with allocation and shape checks. |
| Identity matrix | identity(size) accepts integer sizes from 1 through 3162. |
| Loan duration | loan_payment accepts integer month counts from 1 through 120,000. |
| Compound growth | Principal must be non-negative; annual rate must be greater than -100%; periods per year must be an integer from 1 through 1,000,000; years must be from 0 through 100,000. |
| Benchmark | benchmark_stats(count) accepts integer counts from 1 through 10,000,000. Its milliseconds are machine-dependent CPU timings, not a performance guarantee. |
| Seed range | random_seed accepts finite seeds whose absolute value is at most 9,007,199,254,740,991. |
| Random array | random_array accepts integer counts from 0 through 10,000,000. |
Implementation details: descriptive statistics use Welford-style online updates; median sorts a copy of the data; dot products and sampled integration use compensated summation; the Euclidean norm uses a scaled sum-of-squares calculation; matrix multiplication is blocked in 32-element tiles; determinant uses Gaussian elimination with partial pivoting; inverse and linear solve use scaled partial pivoting. These choices improve numerical behavior but do not make IEEE-754 double arithmetic exact.
21. Complete practical usage: inventory, sales and analysis
This standalone program combines the finance, statistics, vectors, matrices, units, validation, numerical methods and seeded sampling APIs. It uses the language's actual define, func, for/in, array, object and module-call syntax.
import gs_compute;
define products = [
{name: "Keyboard", price: 45, stock: 12, sold: 8},
{name: "Mouse", price: 25, stock: 20, sold: 14},
{name: "Monitor", price: 180, stock: 5, sold: 3}
];
define revenue = [];
define total_stock = 0;
define total_sold = 0;
func sale_total(price, quantity, discount_rate, tax_rate) {
define subtotal = price * quantity;
define discounted = gs_compute.discount(subtotal, discount_rate);
return gs_compute.tax(discounted, tax_rate);
}
for product in products {
define item_revenue = sale_total(product.price, product.sold, 5, 3);
push(revenue, item_revenue);
total_stock = total_stock + product.stock;
total_sold = total_sold + product.sold;
print(product.name);
print(item_revenue);
}
define report = gs_compute.stats(revenue);
print("Revenue mean:");
print(report.mean);
print("Revenue median:");
print(report.median);
print("Inventory remaining:");
print(total_stock);
print("Units sold:");
print(total_sold);
define unit_prices = [45, 25, 180];
define quantities = [8, 14, 3];
print("Gross sales:");
print(gs_compute.dot(unit_prices, quantities));
define sales_matrix = [[45, 25], [180, 60]];
define forecast = gs_compute.matrix_vector(sales_matrix, [8, 3]);
print(forecast);
print("Five kilometres in metres:");
print(gs_compute.convert(5, "km", "m"));
define x = gs_compute.linspace(0, 4, 5);
define y = [0, 1, 4, 9, 16];
print(gs_compute.integrate(x, y));
print(gs_compute.differentiate(x, y));
if (gs_compute.is_close(report.mean, report.median, 0.000001, 0.000001)) {
print("Mean and median are close.");
}
define inverse = gs_compute.matrix_inverse([[4, 7], [2, 6]]);
if (gs_compute.is_null(inverse)) {
print("The matrix could not be inverted.");
} else {
print(inverse);
}
gs_compute.random_seed(2026);
define trial_samples = gs_compute.random_array(6, 0, 100);
print(trial_samples);
print(gs_compute.benchmark_stats(10000));
print(gs_compute.info());
The examples demonstrate API calls and data flow; they are not a substitute for domain validation. Round currency values explicitly at the presentation/business layer if the application requires a fixed decimal currency format. The module uses binary floating-point numbers and does not provide decimal-money arithmetic.
