diff --git a/src/nodes/eval.rs b/src/nodes/eval.rs index f0adfaf..d587064 100644 --- a/src/nodes/eval.rs +++ b/src/nodes/eval.rs @@ -1,6 +1,6 @@ use rug::{ Float, - ops::{AddFrom, DivFrom, MulFrom, PowFrom, SubFrom}, + ops::{AddFrom, CompleteRound, DivFrom, MulFrom, PowFrom, SubFrom}, }; use crate::nodes::{Function, Node, Nodes, Operator}; @@ -143,6 +143,18 @@ impl Function { match self { Self::AbsoluteValue => Float::abs_mut(n), + Self::Factorial => { + if !n.is_integer() { + eprintln!("{n} is not an integer, rounding to calculate its factorial"); + } + + if let Some(int) = n.to_u32_saturating() { + Float::factorial(int).complete_into(n) + } else { + eprintln!("{n} does not fit into a u32, unable to calculate its factorial"); + } + } + Self::SquareRoot => Float::sqrt_mut(n), Self::LogNatural => Float::ln_mut(n), diff --git a/src/nodes/mod.rs b/src/nodes/mod.rs index 8970c31..50b9ffe 100644 --- a/src/nodes/mod.rs +++ b/src/nodes/mod.rs @@ -76,6 +76,8 @@ pub enum Operator { pub enum Function { AbsoluteValue, + Factorial, + SquareRoot, LogNatural, diff --git a/src/nodes/parse.rs b/src/nodes/parse.rs index c5f69e8..324d2bf 100644 --- a/src/nodes/parse.rs +++ b/src/nodes/parse.rs @@ -40,6 +40,8 @@ impl FromStr for Function { match s { "abs" => Ok(Self::AbsoluteValue), + "factorial" => Ok(Self::Factorial), + "sqrt" => Ok(Self::SquareRoot), "ln" => Ok(Self::LogNatural), diff --git a/src/nodes/tests.rs b/src/nodes/tests.rs index 4a8b2db..e5a6a68 100644 --- a/src/nodes/tests.rs +++ b/src/nodes/tests.rs @@ -68,3 +68,8 @@ fn operator_after_parenthesis() { fn abs() { assert_eq!(eval("abs(-1)"), 1.); } + +#[test] +fn factorial() { + assert_eq!(eval("factorial(3)"), 6.); +}