Mathematica 7 compares to other languages

William James w_a_x_man at yahoo.com
Thu Dec 11 03:22:40 CET 2008


Jon Harrop wrote:

> Xah Lee wrote:
> > On Dec 10, 12:37 pm, w_a_x_... at yahoo.com wrote:
> >> Ruby:
> > > 
> >> def norm a
> >>   s = Math.sqrt(a.map{|x|x*x}.inject{|x,y|x+y})
> >>   a.map{|x| x/s}
> >> end
> > 
> > I don't know ruby, but i tried to run it and it does not work.
> > 
> > #ruby
> > def norm a
> >   s = Math.sqrt(a.map{|x|x*x}.inject{|x,y|x+y})
> >   a.map{|x| x/s}
> > end
> > 
> > v = [3,4]
> > 
> > p norm(v) # returns [0.6, 0.8]
> 
> That is the correct answer.
> 
> > The correct result for that input would be 5.
> 
> No, you're confusing normalization with length.

Expanded for easier comprehension.

def norm a
  # Replace each number with its square.
  b = a.map{|x| x*x }
  # Sum the squares. (inject is reduce or fold)
  c = b.inject{|x,y| x + y }
  # Take the square root of the sum.
  s = Math.sqrt( c )
  # Divide each number in original list by the square root.
  a.map{|x| x/s }
end

1.upto(4){|i|
  a = (1..i).to_a
  p a
  p norm( a )
}

--- output ---
[1]
[1.0]
[1, 2]
[0.447213595499958, 0.894427190999916]
[1, 2, 3]
[0.267261241912424, 0.534522483824849, 0.801783725737273]
[1, 2, 3, 4]
[0.182574185835055, 0.365148371670111, 0.547722557505166,
0.730296743340221]



More information about the Python-list mailing list