| > | restart; |
First the Golden ratio program.
| > | evalf(.5*(1+sqrt(5))); |
| > | Golden:=proc(N)
Phi:=2: for j from 1 to N-2 do Phi:=evalf(1+1/Phi): end do: end: |
Warning, `Phi` is implicitly declared local to procedure `Golden`
Warning, `j` is implicitly declared local to procedure `Golden`
| > | Golden(3); |
| > | Golden(4); |
| > | Golden(10); |
| > | Golden(11); |
| > | Golden(12); |
Now the quadratic formula program.
| > | quadro:=proc(a,b,c):
if (a=0) then if (b=0) then print(`Constant function: no roots.`): else x := -c/b: print(`Linear function: one root at `, x): end if: else disc := b^2-4*a*c: if (disc<0) then print(`Negative discriminant: no real roots.`): else if (disc=0) then x := -b/(2*a): print(`Zero discriminant: one repeated root at `, x): else sqd := sqrt(disc): if (b<0) then x1 := (-b+sqd)/(2*a): x2 := (-2*c)/(b-sqd): else if (b>0) then x1 := (-b-sqd)/(2*a): x2 := (-2*c)/(b+sqd): else x1 := sqrt(-c/a): x2 := -x1: end if: end if: print(`Two real roots at`, x1, ` and `, x2): end if: end if: end if: end: |
Warning, `x` is implicitly declared local to procedure `quadro`
Warning, `disc` is implicitly declared local to procedure `quadro`
Warning, `sqd` is implicitly declared local to procedure `quadro`
Warning, `x1` is implicitly declared local to procedure `quadro`
Warning, `x2` is implicitly declared local to procedure `quadro`
| > | quadro(1,2,1); |
| > | quadro(1,2,2); |
Test that it works for four digits.
| > | Digits:=4; |
| > | fsolve(2.1*x^2-42.6*x+1.0=0,x); |
| > | quadro(2.1,-42.6,1.0); |
| > | fsolve(2.0*x^2+55*x-1.0=0,x); |
| > | quadro(2.0,55,-1.0); |