On Sep 1, 2006, at 10:40 AM, Paul Lutus wrote:

> knaveofdiamonds wrote:
>
>> One note of advice - the operator to use is actually ** not ^ as  
>> might
>> be expected:
>>
>> irb> 7 ^ 2 # Gives 5
>> irb> 7 ** 49 # Gives 49
>
> I think you  meant 7 ** 2 = 49, whereas
> 7 ** 49 = 256923577521058878088611477224235621321607
>
> But, since these are integers, we are better off computing n * n,
> not n ** 2. There's really no point (in time efficiency) to explicitly
> raising n to a power p unless n is not an integer or p is  
> relatively large.

#!/usr/bin/env ruby -w

require "benchmark"

TESTS = 1_000_000
Benchmark.bmbm(10) do |results|
   results.report("Exponent:") { TESTS.times { |n| n ** 2 } }
   results.report("Multiply:") { TESTS.times { |n| n * n } }
end
# >> Rehearsal ---------------------------------------------
# >> Exponent:   1.370000   0.000000   1.370000 (  1.372358)
# >> Multiply:   1.730000   0.010000   1.740000 (  1.747647)
# >> ------------------------------------ total: 3.110000sec
# >>
# >>                 user     system      total        real
# >> Exponent:   1.440000   0.000000   1.440000 (  1.452441)
# >> Multiply:   1.760000   0.010000   1.770000 (  1.775988)

James Edward Gray II