Basic floating point support (WIP) #18

Merged
j merged 9 commits from floats into main 2024-09-19 19:27:51 +00:00
Showing only changes of commit b9f4994930 - Show all commits

View File

@ -2,30 +2,27 @@
//! Square root approximation, and example applications //! Square root approximation, and example applications
/// A really small nonzero number /// A really small nonzero number
const EPSILON: f64 // = 8.854... * 10^-12 const EPSILON: f64 = 8.8541878188 / 1000000000000.0;
= 88541878188 as f64
/ 10000000000 as f64
/ 1000000000000 as f64;
/// Calcuates the absolute value of a number /// Calcuates the absolute value of a number
fn f64_abs(n: f64) -> f64 { fn f64_abs(n: f64) -> f64 {
let n = n as f64 let n = n as f64
if n < (0 as f64) { -n } else { n } if n < (0.0) { -n } else { n }
} }
/// Square root approximation using Newton's method /// Square root approximation using Newton's method
fn sqrt(n: f64) -> f64 { fn sqrt(n: f64) -> f64 {
let n = n as f64 let n = n as f64
if n < 0 as f64 { if n < 0.0 {
return 0 as f64 / 0 as f64 // TODO: NaN constant return 0.0 / 0.0 // TODO: NaN constant
} }
if n == 0 as f64 { if n == 0.0 {
return 0 as f64 return 0.0
} }
let z = n let z = n
loop { loop {
let adj = (z * z - n) / (2 as f64 * z) let adj = (z * z - n) / (2.0 * z)
z -= adj z -= adj
if adj.f64_abs() < EPSILON { if adj.f64_abs() < EPSILON {
break z; break z;
@ -42,18 +39,18 @@ fn pythag(a: f64, b: f64) -> f64 {
fn quadratic(a: f64, b: f64, c: f64) -> (f64, f64) { 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; let a = a as f64; let b = b as f64; let c = c as f64;
( (
(-b + sqrt(b * b - 4 as f64 * a * c)) / 2 as f64 * a, (-b + sqrt(b * b - 4.0 * a * c)) / 2.0 * a,
(-b - sqrt(b * b - 4 as f64 * a * c)) / 2 as f64 * a, (-b - sqrt(b * b - 4.0 * a * c)) / 2.0 * a,
) )
} }
fn main() { fn main() {
for i in 0..10 { for i in 0..10 {
println("sqrt(",i,") ≅ ",sqrt(i)) println("sqrt(",i,") ≅ ",sqrt(i as f64))
} }
println("\nPythagorean Theorem") println("\nPythagorean Theorem")
println("Hypotenuse of ⊿(5, 12): ", pythag(5, 12)) println("Hypotenuse of ⊿(5, 12): ", pythag(5.0, 12.0))
println("\nQuadratic formula") println("\nQuadratic formula")
println("Roots of 10x² + 4x - 1: ", quadratic(10, 44, -1)) println("Roots of 10x² + 4x - 1: ", quadratic(10.0, 44.0, -1.0))
} }