c# - Generic Sqrt Implementation -
i'm using miscutils library (thanks marc g. , jon s.) , trying add generic sqrt
function it. problem can reproduced this:
class n<t> { public n(t value) { value = value; } public readonly t value; public static implicit operator t(n<t> n) { return n.value; } public static implicit operator n<t>(t value) { return new n<t>(value); } public static t operator /(n<t> lhs, t rhs) { // operator.divide wrapper around // system.linq.expressions.expression.divide return operator.divide(lhs.value, rhs); } } // fails with: no coercion operator defined // between types 'system.double' , 'n`1[system.single]'. var n = new numeric<float>(1f); var x = operator.dividealternative(n, 1.0); // works n<t> first converted // float via implicit conversion operator var result = n / 1.0;
now, realize why happening, have not yet been able think of way around it. reference, here current sqrt
implementation. have little experience building expression trees.
public static double sqrt<t>(t value) { double oldguess = -1; double guess = 1; while(abs(guess - oldguess) > 1) { oldguess = guess; // first evaluated call dividealternative throws guess = operator.divide( operator.addalternative(guess, operator.dividealternative(value, guess)), 2); } return guess; }
edit: ok, solved on own, in attempt keep question simple possible apparently went far , spent far time answering questions confused people trying help.
so, problem in entirety.
i 2 classes; 1 performs transformations , performs statistical analysis of image data (pixels). let's focus on latter problem same:
abstract class imagestatistics { private readonly object _pixels; public imagestatistics(object pixelarray) { pixels = pixelarray; } // calculate standard deviation of pixel values public double calcstddev(); }
the array of pixels can numeric type. in practice, either float
, int
, ushort
, or byte
. now, because generics cannot things this:
public t add<t>(t lhs, t rhs) { return lhs + rhs; // oops, no operator + t }
i cannot perform sort of statistical analyses on pixel values without casting proper array type. so, need have n sub-classes of imageprocessor
support n pixel types.
well, sucks. love have generic imageprocessor<t>
class has t[]
of pixel data. so, looked miscutils library allow this.
math.sqrt
needs double, why not provide one?
public static double sqrt<t>(t value) { return math.sqrt(convert.todouble(value)); }
you might consider casting dynamic
.
public static double sqrt<t>(t value) { return math.sqrt((dynamic) value); }
this technique can used operators addition:
public static t add<t>(t a, t b) { return (dynamic) + (dynamic) b; }
Comments
Post a Comment