2024-09-18 06:53:04 +00:00
|
|
|
#!/usr/bin/env conlang-run
|
|
|
|
//! Square root approximation, and example applications
|
|
|
|
|
|
|
|
/// A really small nonzero number
|
2024-09-19 19:02:58 +00:00
|
|
|
const EPSILON: f64 = 8.8541878188 / 1000000000000.0;
|
2024-09-18 06:53:04 +00:00
|
|
|
|
|
|
|
/// Calcuates the absolute value of a number
|
|
|
|
fn f64_abs(n: f64) -> f64 {
|
|
|
|
let n = n as f64
|
2024-09-19 19:02:58 +00:00
|
|
|
if n < (0.0) { -n } else { n }
|
2024-09-18 06:53:04 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Square root approximation using Newton's method
|
|
|
|
fn sqrt(n: f64) -> f64 {
|
|
|
|
let n = n as f64
|
2024-09-19 19:02:58 +00:00
|
|
|
if n < 0.0 {
|
|
|
|
return 0.0 / 0.0 // TODO: NaN constant
|
2024-09-18 06:53:04 +00:00
|
|
|
}
|
2024-09-19 19:02:58 +00:00
|
|
|
if n == 0.0 {
|
|
|
|
return 0.0
|
2024-09-18 06:53:04 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
let z = n
|
|
|
|
loop {
|
2024-09-19 19:02:58 +00:00
|
|
|
let adj = (z * z - n) / (2.0 * z)
|
2024-09-18 06:53:04 +00:00
|
|
|
z -= adj
|
|
|
|
if adj.f64_abs() < EPSILON {
|
|
|
|
break z;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Pythagorean theorem: a² + b² = c²
|
|
|
|
fn pythag(a: f64, b: f64) -> f64 {
|
|
|
|
sqrt(a * a + b * b)
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Quadratic formula: (-b ± √(b² - 4ac)) / 2a
|
|
|
|
fn quadratic(a: f64, b: f64, c: f64) -> (f64, f64) {
|
|
|
|
let a = a as f64; let b = b as f64; let c = c as f64;
|
|
|
|
(
|
2024-09-19 19:02:58 +00:00
|
|
|
(-b + sqrt(b * b - 4.0 * a * c)) / 2.0 * a,
|
|
|
|
(-b - sqrt(b * b - 4.0 * a * c)) / 2.0 * a,
|
2024-09-18 06:53:04 +00:00
|
|
|
)
|
|
|
|
}
|
|
|
|
|
|
|
|
fn main() {
|
|
|
|
for i in 0..10 {
|
2024-09-19 19:02:58 +00:00
|
|
|
println("sqrt(",i,") ≅ ",sqrt(i as f64))
|
2024-09-18 06:53:04 +00:00
|
|
|
}
|
|
|
|
println("\nPythagorean Theorem")
|
2024-09-19 19:02:58 +00:00
|
|
|
println("Hypotenuse of ⊿(5, 12): ", pythag(5.0, 12.0))
|
2024-09-18 06:53:04 +00:00
|
|
|
|
|
|
|
println("\nQuadratic formula")
|
2024-09-19 19:02:58 +00:00
|
|
|
println("Roots of 10x² + 4x - 1: ", quadratic(10.0, 44.0, -1.0))
|
2024-09-18 06:53:04 +00:00
|
|
|
}
|