[linux-l] derivative example in groovy

Oliver Bandel oliver at first.in-berlin.de
Di Aug 29 19:00:29 CEST 2006


On Tue, Aug 29, 2006 at 04:22:38PM +0200, Ivan F. Villanueva B. wrote:
[...] 
> ========================================
> #!groovy
> square = {it * it}
> cube = {it * it * it}
> functions = ["square":square, "cube":cube, "sin":{Math.sin(it)}, "cos":{Math.cos(it)}]
> df = {f,x | (f(x + 0.0001) - f(x)) / 0.0001}
> functions.each { name, f ->
>     println name
>     for (i in 1..64) {
>         x = i * 0.01
>         println "x: ${x}, y: ${f(x)}, y': ${df(f,x)}"
>     }
> }
> ========================================
> 
> Ihr habt es gewollt! ;-)
[...]

Nö, habe ich nicht; hatte garnicht mit einer Groovy.Lösung gerechnet.

Sieht aber ganz nett aus.

Weil es anscheinend ums Zeilen spaaren geht, die erste OCaml-version nochmal
überarbeitet und mit Pattern matching etwas kleener:

===================================================================
let derive f x epsilon = (  f(x +. epsilon) -. f x ) /. epsilon
let myderive f x = derive f x 0.001
let quad x = x *. x
let cubic x = x *. x *. x
let fl_titled = [ (sin, "Sinus"); (cos, "Kosinus"); (quad, "Quadrat (Parabel)"); (cubic, "Kubik") ]

let print_stuff p = match p  with
    (f,title) -> Printf.printf "\n\nBerechnung von %s:\n" title;
                   for step = 0 to 63 (* steps *)
                   do  let x = float_of_int step *. 0.1 in
                       Printf.printf "x: %f, y: %f, y': %f\n" x (f x)  (myderive f x)
                   done
let _ = List.iter print_stuff fl_titled
===================================================================

Gruß,
   Oliver



Mehr Informationen über die Mailingliste linux-l