Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

converting type double[][] to float

Tags:

c#

.net

asp.net

I have a function signature like:

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

But I need to covert the double[][] matrix into float values. How is this done as the code can't explicitly convert it?

like image 359
cdub Avatar asked Jun 04 '12 23:06

cdub


People also ask

Can double be converted to float?

Here double is a primitive data type its object can't be used to call the Float class method. If done so it will give the above error.

Can we typecast double to float in Java?

floatValue() to Convert Double to Float in Java. Another way to convert a double value into a float data type in Java is by using the wrapper class Double. This class wraps a primitive data type double in an object.

What is possible lossy conversion from double to float?

As float can have decimal values that don't have corresponding long value. Therefore, we'll receive the same error. The double values can be too large or too small for an int and decimal values will get lost in the conversion. Hence, it is a potential lossy conversion.


2 Answers

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();
}
like image 106
Tim S. Avatar answered Oct 07 '22 16:10

Tim S.


No, you can't convert double to float in place, especially for arrays. You need to create copy with correct type.

like image 26
Alexei Levenkov Avatar answered Oct 07 '22 18:10

Alexei Levenkov