Convert type double [] [] to float

I have a function signature, for example:

static public double[][] G2Sweep(int row1, int row2, double[][] mtx)
{
    mtx = (float) mtx;
}

But I need to hide the double [] [] matrix in float values. How is this done since the code cannot explicitly convert it?

+5
source share
6 answers

No, you cannot convert double to float in place, especially for arrays. You need to create a copy with the correct type.

+4
source
public static float[][] Convert(double[][] mtx)
{
    var floatMtx = new float[mtx.Length][];
    for (int i = 0; i < mtx.Length; i++)
    {
        floatMtx[i] = new float[mtx[i].Length];
        for (int j = 0; j < mtx[i].Length; j++)
            floatMtx[i][j] = (float)mtx[i][j];
    }
    return floatMtx;
}

Or:

public static float[][] Convert(double[][] mtx)
{
    return mtx.Select(i => i.Select(j => (float)j).ToArray()).ToArray();
}
+5
source

float, for,

, , . float ( int, String, MonkeyPoo, - ) . , . .

. A) ( - .Cast<float>), .

+1

, .

, , .

[] []; float [] [], .

.

, , float double?

* , ; webapp ; . , , , Silverlight -, .

+1

Another way you can do this is to use the Array.ConvertAll method:

Array.ConvertAll<double, float>(doubles, d => (float)d);

Performs the same cyclic transformation, but looks better.

+1
source

You can avoid writing a loop manually if you use Linq.

float[][] floats = mtx.Select(r=>r.Select(Convert.ToSingle).ToArray()).ToArray();

EDIT: fixed.

-1
source

All Articles