Posted to tcl by mjanssen at Tue Nov 11 18:12:54 GMT 2008view raw

  1. proc poly {coef f} {
  2. set i 0
  3. set body {}
  4. set coef [lreverse $coef]
  5. foreach c $coef {
  6. append body +$c*pow(\$x,$i)
  7. incr i
  8. }
  9. proc $f x "expr {$body}"
  10. }
  11.  
  12. proc deriv {coef f} {
  13. set i 1
  14. set body {}
  15. set coef [lrange [lreverse $coef] 1 end]
  16. foreach c $coef {
  17. append body +$c*$i*pow(\$x,$i-1)
  18. incr i
  19. }
  20. proc $f x "expr {$body}"
  21. }
  22.  
  23. proc newton {f f' x0} {
  24. # just do 4 iterations
  25. for {set i 0} {$i<10} {incr i} {
  26. set x0 [expr {$x0 - double([$f $x0])/[${f'} $x0]}]
  27. puts $x0
  28. }
  29. return $x0
  30.  
  31. }
  32.  
  33. poly {1 0 -612} f
  34. deriv {1 0 -612} f'
  35. newton f f' 10