Check division by zero in Func <> call

I am trying to process two-dimensional arrays with a dynamic math operator.

This is the method in question:

public float[,] Calculate(int[,] a, int[,] b, Func<int,int,float> compute)
{
   int columns = a.GetLength(0);
   int rows = a.GetLength(1);
   float[,] result = new float[columns,rows];

   for(int i = 0; i < columns; i++)
   {
       for(int j = 0; j < rows; j++)
       {
            result[i,j] = compute(a[i,j], b[i,j]);      
       }
   }
   return result;
}

This method is called the following:

int[,] a = new int[2,3] { {2, 6, 19}, {3, -4, 25}};
int[,] b = new int[2,3] { {12, -2, 11}, {1, -11, 0}};

//1
float[,] c = Calculate(a, b, (x,y) => (x+y));
//2
float[,] c = Calculate(a, b, (x,y) => (x-y));
//3
float[,] c = Calculate(a, b, (x,y) => (x*y));
//4
float[,] c = Calculate(a, b, (x,y) => (x/y));

Now that version 1 through 3 works flawlessly, version 4 will inevitably sooner or later throw an exception. Now one way to handle this is to use the catch try block:

try 
{
    result[i,j] = compute(a[i,j], b[i,j]);      
}
catch(DivideByZeroException ex)
{
    result[i,j] = 0;
}

It looks like I'm using try catch to control the flow, and I would prefer to avoid it (also, the result is incorrect). Is there a way to check the split statement in a function call, and if the statement /, check if the second array contains 0 and just returns null?

+4
source share
2

? if?

float[,] c;

if (b != 0)
    c = Calculate(a, b, (x,y) => (x/y));
else
    c = 0;
+2

, , , 1, , :

static bool IsDivision(Func<int, int, float> func)
{
    var rnd = new Random();

     return  Enumerable.Range(0, 10)
            .Select(x => rnd.Next(100))
            .All(x => Math.Abs(func(x, x) - 1) < 0.000001);
}

, , :

if(IsDivision(compute) &&  b.OfType<int>().Any(x => x == 0)) return null;

, , , (x,y) => 1, , , , :)

+1

Source: https://habr.com/ru/post/1546817/


All Articles