c# - Is this correct for calculating the nth root? -
for positive real numbers rth root given e^(ln(x)/r) negative real numbers if r odd rth root given -e^(ln|x|/r) if r real rth root of negative number not exist
static double rthroot (double r, double x) { double y; if (x > 0) { y = math.exp((math.log(x)) / r); } if (r+1 % 2 == 0) { if (x < 0) { y = -(math.exp((math.log(math.abs(x))) / r)); } } }
there 2 errors in code:
- you not returning value in
rthroot
. need returny
oblige solve additional issue; callrthroot(2, -4)
. want return specific value (double.nan
), want throwargumentexception
or...? if (r + 1 % 2 == 0)
not doing think doing. code equivalentif (r + (1 % 2) == 0)
not want. correct code shouldif ((r + 1) % 2 == 0)
or simpler , more readableif (r % 2 != 0)
standard way check oddity.
Comments
Post a Comment