0 Members and 1 Guest are viewing this topic.
The "fix" function converts a real number to the nearest smaller number.How to round a real number to the nearest larger number?Thanks in advance.
; Rounding function - Doug Broad - 02/19/2003; Additional credits: Joe Burke, Peter Toby; Original name: (defun Round (value to) ...);; Examples:; (ALE_Number_Round 1.11111 1) => 1; (ALE_Number_Round 1.11111 0.1) => 1.1; (ALE_Number_Round 1.11111 0.01) => 1.11; (ALE_Number_Round 1.11111 0.001) => 1.111; (ALE_Number_Round 1.11111 0.0001) => 1.1111; (ALE_Number_Round 1.11111 0.0000001) => 1.11111;; (ALE_Number_Round 1.565656 10) => 0; (ALE_Number_Round 1.565656 1) => 2; (ALE_Number_Round 1.565656 0.1) => 1.6; (ALE_Number_Round 1.565656 0.01) => 1.57; (ALE_Number_Round 1.565656 0.001) => 1.566; (ALE_Number_Round 1.565656 0.0001) => 1.5657; (ALE_Number_Round 1.565656 0.00001) => 1.56566; (ALE_Number_Round 1.565656 0.0000001) => 1.56566;(defun ALE_Number_Round (ImpVal To_Val) (setq To_Val (abs To_Val)) (* To_Val (fix (/ ( (if (minusp ImpVal) - + ) ImpVal (* To_Val 0.5) ) To_Val ) ) ))
@Marc'Antonio AlessiTo be exact: Your function rounds to infinity and not to the nearest largest number.(ALE_NUMBER_ROUND -1.5 1) => -2
$ (type (round 2.49))INT
$ (defun round (val) (float (fix (+ val 0.49999999999999994))))ROUND_$ (type (round 2.49))REAL
_$ (round 1234567890)1234567890_$ (round 12345678901)1.23457e+010
(defun round (num pre / b) ;; Enhanced rounding ;; num -- a number ;; pre -- precision , type in an interg like -1 0 2 ... ;; (round 1.23456789 3) --> 1.235 ;; (round 1.23456789 0) --> 1.0 ;; (round 123456789 -3) --> 1.23457e+008 ;; (round -98764567 -5) --> -9.88e+007 (setq b (expt 10.0 pre)) (/ (fix (+ (* num b) (* 0.5 (sign num)))) b) )(defun sign (x) (cond ((minusp x)-1.)(1.0)))