Roots of a function: Difference between revisions

common lisp entry
(→‎TI-89 BASIC: new example)
(common lisp entry)
Line 205:
}
}</lang>
 
=={{header|Common Lisp}}==
 
{{trans|Perl}}
 
<code>find-roots</code> prints roots (and values near roots) and returns a list of root designators, each of which is either a number <code><var>n</var></code>, in which case <code>(zerop (funcall function <var>n</var>))</code> is true, or a <code>cons</code> whose <code>car</code> and <code>cdr</code> are such that the sign of function at car and cdr changes.
 
<lang lisp>(defun find-roots (function start end &optional (step 0.0001))
(let* ((roots '())
(value (funcall function start))
(plusp (plusp value)))
(when (zerop value)
(format t "~&Root found at ~W." start))
(do ((x (+ start step) (+ x step)))
((> x end) (nreverse roots))
(setf value (funcall function x))
(cond
((zerop value)
(format t "~&Root found at ~w." x)
(push x roots))
((not (eql plusp (plusp value)))
(format t "~&Root found near ~w." x)
(push (cons (- x step) x) roots)))
(setf plusp (plusp value)))))</lang>
 
<pre>> (find-roots #'(lambda (x) (+ (* x x x) (* -3 x x) (* 2 x))) -1 3)
Root found near 5.3588345E-5.
Root found near 1.0000072.
Root found near 2.000073.
((-4.6411653E-5 . 5.3588345E-5)
(0.99990714 . 1.0000072)
(1.9999729 . 2.000073))</pre>
 
=={{header|D}}==
Anonymous user