Friday, 15 June 2012

arrays - Convert decimal[][] to double[][] in C# -



arrays - Convert decimal[][] to double[][] in C# -

i want cast 2d decimal arrays double arrays. done rather efficiently tidy. this looks nice , tidy. how can extend 2d arrays?

am going have loop through first dimension , apply linq/delegate style command or there way less code?

ps: not concerned losing precision past 3-4 decimal places.

update: @ request of comment, proposing although want avoid:

double[][] inputs = new double[inputsarray.length][]; (int = 0; < inputsarray.length; i++) { inputs[i] = array.convertall(inputsarray[i], x => (double)x); }

unfortunately jagged array you'll have convert each array separately, can still done in one-liner:

doublearray = array.convertall(decimalarray, da => array.convertall(da, d => (double)d));

or using linq:

doublearray = decimalarray.select(da => da.select(d => (double)d).toarray()).toarray();

you'll have seek see faster; array.convertall may have optimizations combining delegate , array creation.

benchmarks

to address debate of performance, benchmarked 3 proposed solutions:

array.convert linq loops

here code , results

int = 10000; int j = 1000; random rand = new random(); decimal[][] decimalarray = new decimal[i][]; decimalarray = enumerable.range(1,i).select(i => enumerable.range(1, j).select (j => (decimal)rand.nextdouble()).toarray() ).toarray(); stopwatch s = new stopwatch(); // array.convertall s.start(); var doublearray = array.convertall(decimalarray, da => array.convertall(da, d => (double)d)); s.stop(); s.dump(); // linq s.restart(); doublearray = decimalarray.select(da => da.select(d => (double)d).toarray()).toarray(); s.stop(); s.dump(); // loops s.restart(); doublearray = new double[i][]; for(int = 0; < i; i++) { decimal[] dda = decimalarray[i]; doublearray[i] = new double[dda.length]; double[] da = doublearray[i]; for(int j = 0; j < dda.length; j++) { da[j] = (double)dda[j]; } } s.stop(); s.dump(); method elapsedmilliseconds ------------- ---------------------- array.convert 310 linq 478 loops 287 (7.5% faster array.convert)

you can decide whether 7.5% speed improvement worth 7x amount of code.

c# arrays casting double decimal

No comments:

Post a Comment