agri.yield-per-hectare
Crop yield per hectare and per acre from harvested quantity and field area in any area unit, exactly, as decimal text.
1.0.0 (not the latest) · published 2026-10-03 by charlie · Anterra
Pinned by 17 tests, run in TypeScript, Python and Rust.
What it does
Crop yield per hectare and per acre from the quantity harvested and the area it came from, with the area given in any unit `units.convert` knows (ha, acre, m2, ft2, ...). `yieldPerHectare("85", "10", "ha", 2)` is 8.5 per hectare, 3.44 per acre, 10 ha, 24.71 acres.
The quantity is unitless: the answer is in whatever it was counted in (t, kg, bales, litres of milk from grass), so it works for tonnes of wheat, bales of hay or kg from a trial plot alike. Convert the quantity first with `units.convert` if you need a different mass unit.
For example
yield_per_hectare(85, 10, ha, 2)→ per hectare 8.5, per acre 3.44, hectares 10, acres 24.71 85 t of wheat from 10 ha is 8.5 t/ha and 3.44 t/acreyield_per_hectare(250, 100, acre, 2)→ per hectare 6.18, per acre 2.5, hectares 40.47, acres 100 250 t from 100 acres is 2.5 t/acre and 6.18 t/hayield_per_hectare(12.345, 1.5, ha, 3)→ per hectare 8.23, per acre 3.331, hectares 1.5, acres 3.707 a fractional harvest from a fractional area, to three places
The function
The same function in TypeScript, Python and Rust, pinned by the same tests. Pick your language; the choice follows you around the registry.
pub fn yield_per_hectare(quantity: &str, area: &str, area_unit: &str, decimals: i64) -> YieldPerArea
| quantity | string | harvested amount as plain decimal text ("85", "12.345"), in whatever unit you count: t, kg, bales, litres |
| area | string | the area it came from, plain decimal text, more than zero |
| area_unit | string | an area symbol of units.convert: ha, acre, m2, km2, ft2, yd2 ... |
| decimals | int | 0 to 12; every result is rounded half up to this many places |
| returns | YieldPerArea |
The type it declares, generated into your project
/// The yield both ways, and the area both ways, as decimal text with trailing zeros trimmed.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct YieldPerArea {
/// quantity per hectare, in the quantity's unit
pub per_hectare: String,
/// quantity per international acre (4046.8564224 m²)
pub per_acre: String,
pub hectares: String,
pub acres: String,
}
Your code names it in one line, in the file that uses it
fune!(agri.yield-per-hectare@^1); // then call yield_per_hectare(…)
Imports name this capability’s declared dependencies, which fune builds next to it in your project; each one links to its page.
use super::funejson::Value; ← the fune runtime: the JSON value the test vectors use; fune build keeps it only where a signature takes one
use super::units_convert::convert_units; ← from units.convert ^1.0.0 · built alongside by fune
// digits / 10^scale
#[derive(Clone, Copy)]
struct Decimal {
digits: i128,
scale: u32,
}
fn is_decimal(text: &str) -> bool {
let mut parts = text.splitn(2, '.');
let digits = |s: &str| !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit());
digits(parts.next().unwrap_or("")) && parts.next().map_or(true, digits)
}
fn parse(name: &str, text: &str, limited: bool) -> Decimal {
if !is_decimal(text) {
panic!("{} must be plain non-negative decimal text like \"12.5\", received \"{}\"", name, text);
}
let mut parts = text.splitn(2, '.');
let whole = parts.next().unwrap_or("");
let fraction = parts.next().unwrap_or("").trim_end_matches('0');
let joined = format!("{}{}", whole, fraction);
let significant = joined.trim_start_matches('0');
if limited && (significant.len() > 12 || fraction.len() > 6) {
panic!("{} \"{}\" has too many digits: at most 12 significant digits and 6 decimal places", name, text);
}
if significant.len() > 30 {
panic!("{} \"{}\" has too many digits", name, text);
}
Decimal {
digits: if significant.is_empty() { 0 } else { significant.parse::<i128>().unwrap() },
scale: fraction.len() as u32,
}
}
// Inputs are capped at 12 significant digits and 6 places and the largest
// unit factor is the square mile (2589988110336 / 10^6 m²), so after the
// powers of ten cancel nothing here passes about 1e33; the checks make any
// breach loud instead of wrapping.
fn mul(a: i128, b: i128) -> i128 {
a.checked_mul(b).unwrap_or_else(|| panic!("value too large to divide exactly"))
}
fn ratio(top: &[Decimal], bottom: &[Decimal]) -> (i128, i128) {
let (mut num, mut den, mut exponent) = (1i128, 1i128, 0i64);
for d in top {
num = mul(num, d.digits);
exponent -= d.scale as i64;
}
for d in bottom {
den = mul(den, d.digits);
exponent += d.scale as i64;
}
if exponent > 0 {
num = mul(num, 10i128.pow(exponent as u32));
} else {
den = mul(den, 10i128.pow((-exponent) as u32));
}
(num, den)
}
// Long division, one digit at a time, rounded half up, trailing zeros trimmed.
fn to_text((num, den): (i128, i128), decimals: i64) -> String {
let mut whole = num / den;
let mut remainder = num % den;
let mut fraction: i128 = 0;
for _ in 0..decimals {
remainder = mul(remainder, 10);
fraction = fraction * 10 + remainder / den;
remainder %= den;
}
if mul(remainder, 2) >= den {
fraction += 1;
if fraction == 10i128.pow(decimals as u32) {
fraction = 0;
whole += 1;
}
}
let mut text = whole.to_string();
if decimals > 0 {
let padded = format!("{:0>width$}", fraction, width = decimals as usize);
let shown = padded.trim_end_matches('0');
if !shown.is_empty() {
text.push('.');
text.push_str(shown);
}
}
text
}
/// Yield per hectare and per acre, exactly.
///
/// The area unit's size comes from units.convert as exact decimal text
/// (1 acre = 4046.8564224 m²), so every answer is one exact fraction rounded
/// once. In floats, 1.005 t from 1 ha is 1.00 t/ha to two places; here it is
/// 1.01.
///
/// # Panics
/// Panics on malformed or over-long decimals, a zero area, a unit that is not
/// an area, or `decimals` outside 0..=12.
pub fn yield_per_hectare(quantity: &str, area: &str, area_unit: &str, decimals: i64) -> YieldPerArea {
let q = parse("quantity", quantity, true);
let a = parse("area", area, true);
if !(0..=12).contains(&decimals) {
panic!("decimals must be a whole number from 0 to 12, received {}", decimals);
}
let unit = parse("unit size", &convert_units("1", area_unit, "m2", 12), false);
if a.digits == 0 {
panic!("area must be greater than zero");
}
let acre = parse("acre", &convert_units("1", "acre", "m2", 12), false);
let hectare = Decimal { digits: 10000, scale: 0 };
YieldPerArea {
per_hectare: to_text(ratio(&[q, hectare], &[a, unit]), decimals),
per_acre: to_text(ratio(&[q, acre], &[a, unit]), decimals),
hectares: to_text(ratio(&[a, unit], &[hectare]), decimals),
acres: to_text(ratio(&[a, unit], &[acre]), decimals),
}
}
pub fn yield_per_area_to_value(y: &YieldPerArea) -> Value {
Value::obj(vec![
("perHectare", Value::str(&y.per_hectare)),
("perAcre", Value::str(&y.per_acre)),
("hectares", Value::str(&y.hectares)),
("acres", Value::str(&y.acres)),
])
}
pub fn fune_vector(args: &[Value]) -> Value {
let text = |v: &Value, name: &str| -> String {
match v {
Value::Str(s) => s.clone(),
other => panic!("{} must be plain non-negative decimal text like \"12.5\", received {:?}", name, other),
}
};
let decimals = match &args[3] {
Value::Int(i) => *i,
other => panic!("decimals must be a whole number from 0 to 12, received {:?}", other),
};
yield_per_area_to_value(&yield_per_hectare(
&text(&args[0], "quantity"),
&text(&args[1], "area"),
args[2].as_str(),
decimals,
))
}Install
fune build
With that line in your source, in a Rust project (language rust in fune.project), fune build resolves it and its 1 dependency, pins them in fune.lock, downloads only the Rust package of each, and builds the code above into your project’s .fune/build, one readable file per capability with a header linking back here. A crate’s build.rs runs it before every compile. Or pin a range in fune.project and build in one step:
fune add agri.yield-per-hectare
The manifest, vectors and README with only the Rust implementation. Install it without the registry with fune add ./agri.yield-per-hectare-1.0.0-rust.fune, or fetch it from a terminal with fune pull agri.yield-per-hectare@1.0.0:rust.
The whole function, every language, is one file too: agri.yield-per-hectare-1.0.0.fune, 21,317 bytes, sha256 86db303ddce71a7afc9145a68cf71b1b7636d48c41535e4f40fedce92a88a6ca. It installs into a project of any language.
Customise it in your app
The seams this capability offers. Put a marker directly above a function of your own and fune build wires it into the built code; the package on the registry is not changed, the built file’s header lists it under CUSTOMISED, and fune hooks lists every hook in the project. How hooks work.
before — your function gets the arguments and returns them, changed or not, or throws to refuse the call.
// fune: before agri.yield-per-hectare
after — your function gets the result and the arguments, and returns the final result.
// fune: after agri.yield-per-hectare
replace — inside this capability’s code only, calls to a dependency go to your function, with the same signature. Other capabilities that use it are unaffected; write in * to replace it everywhere.
// fune: replace units.convert in agri.yield-per-hectare
step — your function runs at a numbered point inside the function’s body, receives the in-scope values it names as parameters, and may return replacements. List the points with fune show agri.yield-per-hectare --steps.
// fune: step agri.yield-per-hectare after <n|label>
Tests
A version published now needs at least 8 tests for every function, and one that expects the error for each function that throws; the registry refuses it otherwise. fune verify --all runs each case in TypeScript, Python and Rust, and a project runs them again with fune verify. This page lists the cases; it does not run them. The exact JSON is vectors.json.
| Case | Arguments | Expected | |
|---|---|---|---|
| 85 t of wheat from 10 ha is 8.5 t/ha and 3.44 t/acre | 85, 10, ha, 2 | → | per hectare 8.5, per acre 3.44, hectares 10, acres 24.71 |
| 250 t from 100 acres is 2.5 t/acre and 6.18 t/ha | 250, 100, acre, 2 | → | per hectare 6.18, per acre 2.5, hectares 40.47, acres 100 |
| a fractional harvest from a fractional area, to three places | 12.345, 1.5, ha, 3 | → | per hectare 8.23, per acre 3.331, hectares 1.5, acres 3.707 |
| a trial plot in square metres | 500, 2500, m2, 2 | → | per hectare 2000, per acre 809.37, hectares 0.25, acres 0.62 |
| 1.005 t/ha rounds half up to 1.01, where a float says 1.00 | 1.005, 1, ha, 2 | → | per hectare 1.01, per acre 0.41, hectares 1, acres 2.47 |
| nothing harvested is zero per hectare | 0, 3.2, ha, 2 | → | per hectare 0, per acre 0, hectares 3.2, acres 7.91 |
| zero decimals rounds to whole numbers, half up | 7, 3, ha, 0 | → | per hectare 2, per acre 1, hectares 3, acres 7 |
| a garden plot in square feet: 9.7 kg from 30.25 ft² is exactly 13968 kg/acre | 9.7, 30.25, ft2, 4 | → | per hectare 34515.6797, per acre 13968, hectares 0.0003, acres 0.0007 |
| trailing zeros are trimmed and leading zeros accepted | 085.000, 010, ha, 3 | → | per hectare 8.5, per acre 3.44, hectares 10, acres 24.711 |
| zero area is an error | 85, 0, ha, 2 | → | error: area must be greater than zero |
Show the other 7 tests
| Case | Arguments | Expected | |
|---|---|---|---|
| a unit that is not an area is an error | 85, 10, kg, 2 | → | error: cannot convert kg (mass) to m2 (area) |
| an unknown unit is an error | 85, 10, hectare, 2 | → | error: unknown unit "hectare" |
| a negative quantity is an error | -5, 10, ha, 2 | → | error: quantity must be plain non-negative decimal text |
| exponent notation is an error | 1e3, 10, ha, 2 | → | error: quantity must be plain non-negative decimal text |
| more than 12 significant digits is an error | 1234567890123, 10, ha, 2 | → | error: has too many digits |
| more than 6 decimal places is an error | 85, 10.1234567, ha, 2 | → | error: has too many digits |
| decimals above 12 is an error | 85, 10, ha, 13 | → | error: decimals must be a whole number from 0 to 12 |
More from the author
## Exactness
Quantity and area arrive as decimal text, and the size of the area unit comes from `units.convert` as exact decimal text (`convertUnits("1", "acre", "m2", 12)` is `"4046.8564224"`, the international acre). Each result is therefore one exact fraction, rounded once, half up, to `decimals` places, with trailing zeros trimmed: `"8.5"`, not `"8.50"`. In floating point 1.005 t from 1 ha shows as 1.00 t/ha to two places; this gives 1.01.
The acre is the international acre (43,560 international square feet, 4046.8564224 m²), as in `units.convert`; the US survey acre was retired at the end of 2022.
## Limits
Quantity and area are plain non-negative decimal text: digits with an optional fractional part, no sign, separators or exponent, at most 12 significant digits and 6 decimal places. The area must be more than zero; a quantity of zero is a yield of zero. `decimals` is 0 to 12. These limits keep the Rust port exact in `i128`.
## Sources
The unit sizes are `units.convert`'s: NIST SP 811 (2008), Appendix B, and NIST, "U.S. Survey Foot: Revised Unit Conversion Factors" (the acre as 4046.8564224 m²); 1 ha = 10,000 m² by definition.
Files
| Path | Bytes |
|---|---|
| README.md | 1,726 |
| impl/python.py | 3,331 |
| impl/rust.rs | 5,308 |
| impl/typescript.ts | 3,357 |
| vectors.json | 3,837 |