r - Quadratic Function with Complex Numbers -
i'm writing function in r needs solve basic quadratic equation , gives roots. need print out imaginary numbers if applicable. below code. give me advice on how improve coding?
quad = function(a, b, c){ d = b^2 - 4*a*c if (d < 0){ cat("the roots are", x, "and", y,"i\n"); z < - complex(real = x, imaginary = y) return(); } x = (-b - d^0.5)/(2*a) y = (-b + d^0.5)/(2*a) cat("the 2 roots are", x, "and", y, "\n"); } just keep in mind i'm incredibly new r programmer, , aware incredibly simple code. advice appreciated.
you can use simple code.
quadr=function(a,b,c){ d=b^2-4*a*c m=ifelse(d<0,complex(1,0,sqrt(abs(k))),sqrt(k)) c((-b+m)/(2*a),(-b-m)/(2*a)) } quadr(1,1,6) [1] -0.5+2.397916i -0.5-2.397916i quadr(1,1,-6) [1] 2 -3
Comments
Post a Comment