// Floating-point helpers: roots, distances, statistics and tolerant comparison.
import std.io.println;
import std.math.float;
def close_to(value: f64, expected: f64): bool {
return approx_eq_f64(value, expected, 0.000001, 0.0);
}
def report(label: string, ok: bool): void {
if (ok) { println(label); } else { println("unexpected result"); };
}
def main(): int {
report("hypot(3, 4) is 5", close_to(hypot_f64(3.0, 4.0), 5.0));
let samples: vector f64 = [2.0, 4.0, 4.0, 4.0, 5.0, 5.0, 7.0, 9.0];
match mean_f64(&samples) with
| option.some(mean) -> { report("mean is 5", close_to(mean, 5.0)); }
| option.none -> { };
match stddev_population_f64(&samples) with
| option.some(spread) -> { report("standard deviation is 2", close_to(spread, 2.0)); }
| option.none -> { };
report("sqrt(2) squared is 2", close_to(sqrt_f64(2.0) * sqrt_f64(2.0), 2.0));
report("a circle of radius 1 has area pi", close_to(pi_f64() * 1.0 * 1.0, 3.141592653589793));
report("0.1 + 0.2 is close to 0.3", close_to(0.1 + 0.2, 0.3));
return 0;
}// دوال الأعداد العائمة: الجذور والمسافات والإحصاء والمقارنة بسماحية.
استورد std.io.println;
استورد std.math.float;
عرف قريب_من(القيمة: ع64, المتوقع: ع64): منطقي {
أرجع قريب64(القيمة, المتوقع, 0.000001, 0.0);
}
عرف أبلغ(التسمية: نص, سليم: منطقي): فراغ {
إذا (سليم) { اطبع_سطر(التسمية); } وإلا { اطبع_سطر("نتيجة غير متوقعة"); };
}
عرف الرئيسية(): عدد {
أبلغ("الوتر لضلعين 3 و4 هو 5", قريب_من(وتر64(3.0, 4.0), 5.0));
دع العينات: متجه ع64 = [2.0, 4.0, 4.0, 4.0, 5.0, 5.0, 7.0, 9.0];
طابق متوسط64(&العينات) مع
| اختياري.موجود(المتوسط) -> { أبلغ("المتوسط 5", قريب_من(المتوسط, 5.0)); }
| اختياري.لا_شيء -> { };
طابق انحراف_معياري_مجتمع64(&العينات) مع
| اختياري.موجود(الانتشار) -> { أبلغ("الانحراف المعياري 2", قريب_من(الانتشار, 2.0)); }
| اختياري.لا_شيء -> { };
أبلغ("مربع جذر 2 هو 2", قريب_من(جذر_تربيعي64(2.0) * جذر_تربيعي64(2.0), 2.0));
أبلغ("مساحة دائرة نصف قطرها 1 هي باي", قريب_من(باي64() * 1.0 * 1.0, 3.141592653589793));
أبلغ("0.1 + 0.2 قريب من 0.3", قريب_من(0.1 + 0.2, 0.3));
أرجع 0;
}
Run it
With the interpreter, without compiling:
./build/sultanc run examples/en/math/float_math.snOr compile it to an executable:
./build/sultanc examples/en/math/float_math.sn -o build/example && ./build/example