28 September 2007

Playing with float arithmetics with Ruby: how to truncate decimals

I needed to truncate a float to 4 decimals because I am using geocoding in my app and Google map returns coordinates with a lot of decimals ...

After reading this post in the ruby-talk mailing list, I decided to take a break in my development and write the following code :


require 'benchmark'

class Float
def truncate_decimals_with_printf(number_of_decimals_after_dot)
("%.#{number_of_decimals_after_dot}f" % self).to_f
end

def truncate_decimals_with_regexp(number_of_decimals_after_dot)
match = Regexp.compile("\\d*." + "\\d" * number_of_decimals_after_dot).match(self.to_s)
match[0].to_f
end

def truncate_decimals_with_arithmetic(number_of_decimals_after_dot)
x = 10 ** number_of_decimals_after_dot
(self * x).round.to_f / x
end
end

describe "Float.truncate_decimals" do

it "could truncate decimals using printf" do
1.12349.truncate_decimals_with_printf(4).should == 1.1234
end

it "could truncate decimals using a regexp" do
1.12349.truncate_decimals_with_regexp(4).should == 1.1234
end

it "could truncate decimals using arithmetic" do
1.12349.truncate_decimals_with_arithmetic(4).should == 1.1234
end

it "Benchmark:" do
Benchmark.bm(10) do |timer|
timer.report('arithmetic') { 1.12349.truncate_decimals_with_arithmetic(4) }
timer.report('printf') { 1.12349.truncate_decimals_with_printf(4) }
timer.report('regexp') { 1.12349.truncate_decimals_with_regexp(4) }
end
end

end



The result:

Float.truncate_decimals
- could truncate decimals using printf (FAILED - 1)
- could truncate decimals using a regexp
- could truncate decimalsusing arithmetic (FAILED - 2)
user system total real
arithmetic 0.000000 0.000000 0.000000 ( 0.000015)
printf 0.000000 0.000000 0.000000 ( 0.000017)
regexp 0.000000 0.000000 0.000000 ( 0.000028)
- Benchmark:

1)
'Float.truncate_decimals could truncate decimals using printf' FAILED
expected: 1.1234,
got: 1.1235 (using ==)
/home/jeanmichel/ruby/projects/iss2.0/spec/models/float_spec.rb:22:

2)
'Float.truncate_decimals could truncate using arithmetic' FAILED
expected: 1.1234,
got: 1.1235 (using ==)
/home/jeanmichel/ruby/projects/iss2.0/spec/models/float_spec.rb:30:

Finished in 0.008598 seconds

4 examples, 2 failures

The arithmetric solution is the fastest! Faster than printf ! Computers are good at division and multiplication ;-) The regexp is damned slow, however it's the only one which actually fullfill the specs ;-)

Any idea how to change other implementations ?

Today, I have lost a few hours because the arithmetic implementation was working on my dev box, a Linux 2.6.20-16-386 i686 GNU with a ruby 1.8.5 (2006-08-25) [i486-linux] and NOT at all on my production server, a
Linux i686 i686 i386 GNU/Linux with a ruby 1.8.4 (2005-12-24) [i386-linux] ...

At the end, I used the printf version, which is OK because I don't care about the rounding...

Most important rule: you should always get a stage server IDENTICAL to your production server and run the tests / specs on it before deploying!

17 September 2007

Hola RailsConf Europa

Escribo este mensaje para los que hayan visto mi mensaje en el message board, y que quieran saber un poco más sobre 21 croissants.

Soy un programador Rails desde el 2006 y me encantan el "testing", BDD, RSpec, selenium, etc ... Echa un ojo a mi ponencia a Rails Hispana en el 2006

Para resumir, después de 5 años de Java, en Paris, Londres y Barcelona, empiezo mi actividad de autónomo con eco-union, una asociación ecologista y estoy buscando clientes (ONGs / Asociaciones / Servicios públicos o PYMES.

Me gustaría escribir tutoriales sobre RSpec y introducir este framework. Me gustaría saber que te parece el Rspec y el testing.

Mándame un mensaje si quieres quedar en la RailsConf.

Hasta pronto!

Jean-Michel

Bonjour RailsConf Europe

J'écris ce post au cas oú tu sois tombé sur ma carte de visite dans le message board de la RailsConf et tu voudrais en savoir un peu plus sur 21croissants.

En 1 ligne, je développe avec Rails depuis 1 an et des brouettes et je suis passionné par le "testing", BDD, RSpec, selenium, etc ...

Pour résumer en quelque lignes, après 5 ans de java successivement à Paris, Londres puis Barcelone, je commence mon activité de freelancer dans le cadre de eco-union, association écologiste à Barcelone et je recherche des clients potentiels (ONGs/ associations / services publiques ou PMEs). Je n'ai pas encore décidé si j'allais rester en Espagne, et je suis donc intéressé par toutes les entreprises francophones (petite structures!) qui utilisent Rails et une méthode Agile.

Je recherche également des partenaires freelancers intéressés par offrir des prestations de formation sur Ruby on Rails en français ou en anglais pour 2008.

J'ai l'intention d'écrire des mini-tutoriels (screencasts) sur RSpec et présenter ce framework lors de la prochaine Paris On Rails. N'hésite pas à me donner ton point de vue sur ce framework et le testing en général.

Envoie moi un email si tu as envie de me rencontrer en personne pendant la RailsConf.

A bientôt j'espère!

Jean-Michel

03 September 2007

Cheap Rails hosting

I pay about 10$ / month for the hosting of my apps at site5
So far, I haven't had any major problem but I wonder if it's not time to move to a more powerful configuration with a more qualified support.

I am not saying site5 support is not competent but they are a bit slow. Most of the time, there are different people who reply to my questions. I suspect they only have a few rails experts and a lot of people in their support with no specific specialization...

Moreover, they are still using ruby 1.8.4, rubygems 0.9.2 and rails 1.1.6, more than 6 months after the release of Rails 1.2.3!!!

When asking about moving to mongrel instead of the quite unstable fcgi, they reply they have not planned it ...

Any host to recommand apart from Railsmachine?

I am going to try the startup at primetime, a norwegian company whose engineers are top-notch gurus in linux and Rails.

It happens they are also friends of mine from Oslo ;-)