Koni Marti
12/28/2007 3:03:00 PM
Hiato Xaero wrote:
> Thanks :)
>
> Wow, Ruby is really awesome and these different methods are prime examples.
> Thanks Sander and Sebastien for making my script officially Rubified :)
>
> (I'm stuck in an eternal loop of procedural programming because of Delphi :(
> )
>
Nice example. Ruby is definitely awesome!
It also allows you to get rid of possible computational bottelnecks by
simple c extensions (which makes Ruby ideally for scientific purposes as
well).
-- Koni
Check this out, it makes the script 2-3 times faster and I'm sure one
can still improve that:
* mandelbrot.rb
require 'Mandelbrot'
f=Mandelbrot.new
(-24..23).each do |i|
puts((-64..62).inject("") do |s,k|
p = x = y = 0
while ((x*x)+(y*y)<4)
x, y = f.calculate(x,y,k,i)
#x, y = x*x - y*y + (k-23)/43.5, 2*x*y + i/22.0
p += 6
break unless p<260
end
s << (p > 250 ? ' ' : (65 + (p-1)/10).chr)
end)
end
* mandelbrot.c
#include <ruby.h>
static VALUE rb_mandel;
static VALUE rb_calculate(VALUE self, VALUE xval, VALUE yval, VALUE
kval, VALUE ival)
{
VALUE result;
double x, y, k, i;
x = NUM2DBL(xval);
y = NUM2DBL(yval);
k = NUM2DBL(kval);
i = NUM2DBL(ival);
result = rb_ary_new2(2);
rb_ary_push(result, rb_float_new((x*x - y*y + (k-23.0)/43.5)));
rb_ary_push(result, rb_float_new((2.0*x*y + i/22.0)));
return result;
}
void Init_mandelbrot(void ) {
rb_mandel = rb_define_class("Mandelbrot",rb_cObject);
rb_define_method(rb_mandel, "calculate", rb_calculate, 4);
}
* extconf.rb
require 'mkmf'
create_makefile('mandelbrot')