2017-09-11 37 views
0

我在R中編寫了一個函數,它需要求解基本的二次方程並給出根。如果適用,我需要打印出虛數。以下是我的代碼。任何人都可以告訴我如何改進我的編碼?具有複數的二次函數

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 two roots are", x, "and", y, "\n"); 
} 

只要記住我是一個令人難以置信的新的R程序員,我知道這是一個非常簡單的代碼。任何建議將不勝感激。

回答

0

行中:cat("The roots are", x, "and", y,"i\n");它將搜索未聲明的xy。它也將計算出的根源,即使D<0所以最好使用IF,ELSE塊,如:

if (D < 0){ 
     # cat("The roots are", x, "and", y,"i\n"); 
     # z < - complex(real = x, imaginary = y) 
     cat("imaginary roots") 
     } 
     else{ 
     x = (-b - D^0.5)/(2*a) 
     y = (-b + D^0.5)/(2*a) 
     cat("The two roots are", x, "and", y, "\n"); 
     } 
+0

我的代碼現在完美運行,但當我嘗試執行quad(1,0,5)或類似操作時,它不會打印出結果。它只會打印出我寫的內容。任何想法是什麼? –

0

你可以使用這個簡單的代碼。

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