Mathematica 7 compares to other languages

Brian Blais bblais at bryant.edu
Thu Dec 11 15:01:37 EST 2008


On Dec 11, 2008, at 13:41 , Xah Lee wrote:

> On Dec 10, 2:47 pm, John W Kennedy <jwke... at attglobal.net> wrote:
>> Xah Lee wrote:
>>> In lisp, python, perl, etc, you'll have 10 or so lines. In C or  
>>> Java,
>>> you'll have 50 or hundreds lines.
>>
>> C:
>>
>> #include <stdlib.h>
>> #include <math.h>
>>
>> void normal(int dim, float* x, float* a) {
>>     float sum = 0.0f;
>>     int i;
>>     float divisor;
>>     for (i = 0; i < dim; ++i) sum += x[i] * x[i];
>>     divisor = sqrt(sum);
>>     for (i = 0; i < dim; ++i) a[i] = x[i]/divisor;
>>
>> }
>
> i don't have experience coding C. The code above doesn't seems to
> satisfy the spec. The input should be just a vector, array, list, or
> whatever the lang supports.
> The output is the same datatype of the same dimension.
>


This does satisfy it, depending on what you mean by "return".  In C  
it is more common to do in-place assignment of pointers, rather than  
return values.  So in the code above

float *x  is a list, if you will, of floats
float *a  is a list also
dim is the length of the list

it assumes that the outside code has already allocated the space for  
a and x.  Instead of returning "a", it modifies the list in place.   
(for C purists, I know it's not a list, but that's just a convenient  
term).

Also, for python, I wouldn't choose to code it in one line, when 2 is  
clearer:

def normal(x):

     square=sqrt(sum([val**2 for val in x]))
     return [val/square for val in x]

or, as others have pointed out, for numerical work I'd just use numpy:

from numpy import *

def normal(x):
    return x/sqrt(x.sum())

or something like that.


				bb




-- 
Brian Blais
bblais at bryant.edu
http://web.bryant.edu/~bblais



-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20081211/d9dcda37/attachment-0001.html>


More information about the Python-list mailing list