Posted to tcl by Florentis at Sat Sep 26 18:17:13 GMT 2026view raw

  1. # Rework of a Tcl lib math polynomial proc
  2. # the proc is in arithmetic syntax
  3. # and use commands lmap, foreach, return
  4.  
  5. proc multPolyn_ari {polyn1 polyn2} {(
  6.  
  7. [llength $polyn1] == 1 && [string is double -strict $polyn1] ? ( polyn1 = [polynomial $polyn1] ):;
  8. [llength $polyn2] == 1 && [string is double -strict $polyn2] ? ( polyn2 = [polynomial $polyn2] ):;
  9.  
  10. [lindex $polyn1 0] != "POLYNOMIAL" || [lindex $polyn2 0] != "POLYNOMIAL" ?
  11. [return -code error "Both arguments must be polynomials or a real number"] :;
  12.  
  13. coeffs1 = [lindex $polyn1 1];
  14. coeffs2 = [lindex $polyn2 1];
  15.  
  16. #
  17. # Take care of the null polynomial
  18. #
  19. $coeffs1 == {} || $coeffs2 == {} ? [ return [polynomial ""] ]:;
  20.  
  21. zeros = lmap c $coeffs1 {(0.0)};
  22.  
  23. new_coeffs = [lrepeat [( [llength $zeros]+[llength $coeffs2]-1 )] 0.0];
  24.  
  25. idx = 0;
  26. foreach c $coeffs1 {(
  27. term_coeffs = lmap c2 $coeffs2 {($c*$c2)};
  28. term_coeffs = [lreplace $zeros $idx $idx {*}$term_coeffs];
  29. sum_coeffs = lmap t $term_coeffs n $new_coeffs {($t+$n)};
  30. new_coeffs=$sum_coeffs;
  31. [incr idx];
  32. )};
  33.  
  34. return [list POLYNOMIAL $new_coeffs];
  35. )}

Add a comment

Please note that this site uses the meta tags nofollow,noindex for all pages that contain comments.
Items are closed for new comments after 1 week