2012-07-25 46 views
1

這裏是我的代碼來解決方程:解方程,奇怪的結果

fx=function(x){ x^3-x-3} 
solve=function(a,b,eps){ 
    if(abs(fx(a))<0.00001) return(list(root=a,fun=fx(a)))  
    else if(abs(fx(b))<0.00001) return(list(root=b,fun=fx(b))) 
    else if (fx(a)*fx(b)>0) return(list(root="failed to find")) 
    if (a>b){ 
     c<-a 
     a<-b 
     a<-b}  
    while(b-a>eps){ 
     x=(a+b)/2 
     if (fx(x)==0) {return(list(root=x,fun=fx(x))) } 
     else if (fx(a)*fx(x)<0) {b=x }   
     else {a=x}} 
    myroot=(a+b)/2 
    return(list(root=myroot,value=fx(myroot))) 
} 

> solve(1,3,1e-8) 
$root 
[1] 1.6717 

$value 
[1] 2.674228e-08 

> fx(1.6717) 
[1] 8.73813e-07 

爲什麼fx(1.6717) != $value,我想知道原因
8.73813e-07!=2.674228e-08

我該如何修改:return(list(root = myroot,value = fx(myroot)))
使我的根更多數字?

回答

2

當R打印一個值時,默認使用digits=3,即打印3位有效數字。這意味着您在查看結果時會解釋錯誤。

試試這個:

x <- solve(1,3,1e-8) 

print(x[[1]], digits=9) 
[1] 1.67169989 

現在代替實際返回的值到您的函數:

fx(x[[1]]) 
[1] 2.674228e-08 

現在值匹配。

總之,在解釋函數的打印結果時,會出現舍入錯誤。


如下您可以跟蹤在R幫助文件此行爲:

?print 

將指向你

?print.default 

其中有這樣說的digits說法:

digits:數字的非空值指定最小nu需要打印的數位有效數字。缺省值NULL使用getOption(數字)。 (有關複數的解釋請參閱signif。)非整數值將向下舍入,只接受大於等於1且不大於22的值。

0

試試看,並看看abprint()

fx=function(x){ x^3-x-3} 
solve=function(a,b,eps){ 
    if(abs(fx(a))<0.00001) return(list(root=a,fun=fx(a)))  
    else if(abs(fx(b))<0.00001) return(list(root=b,fun=fx(b))) 
    else if (fx(a)*fx(b)>0) return(list(root="failed to find")) 
    if (a>b){ 
     c<-a 
     a<-b 
     a<-b}  
    while(b-a>eps){ 
     x=(a+b)/2 
     if (fx(x)==0) {return(list(root=x,fun=fx(x))) } 
     else if (fx(a)*fx(x)<0) {b=x }   
     else {a=x}} 
    myroot=(a+b)/2 
    print(a,digits=20) 
    print(b,digits=20) 
    return(list(root=myroot,value=fx(myroot))) 
} 

有一輪。