# Mathematica 7 compares to other languages

Bakul Shah bakul+usenet at bitblocks.com
Fri Dec 12 22:19:29 CET 2008

```George Neuner wrote:
> On Thu, 11 Dec 2008 10:41:59 -0800 (PST), Xah Lee <xahlee at gmail.com>
> 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.
>
> Then why do you talk about it as if you know something?
>
>> The code above doesn't seems to satisfy the spec.
>
> It does.
>
>> The input should be just a vector, array, list, or
>> whatever the lang supports. The output is the same
>> datatype of the same dimension.
>
> C's native arrays are stored contiguously.  Multidimensional arrays
> can be accessed as a vector of length (dim1 * dim2 * ... * dimN).
>
> This code handles arrays of any dimensionality.  The poorly named
> argument 'dim' specifies the total number of elements in the array.
>
> George

Only if the length in each dimension is known at compile time (or
in C99, if this is an automatic array). When this is not the case,
you may have to implement something like the following (not the only
way, just one way):

float** new_matrix(int rows, int cols) {
float** m = malloc(sizeof(float*)*rows);
int i;
for (i = 0; i < rows; i++)
m[i] = malloc(sizeof(float)*cols);
return m;
}

In this case normal() fails since matrix m is not in a single
contiguous area.

But I suspect Xah is complaining because the function doesn't
*return* a value of the same type; instead you have to pass in
the result vector. But such is life if you code in C!

```