[R] Help in Bissection algorithm
William Dunlap
wdunlap at tibco.com
Thu Nov 29 21:26:31 CET 2012
And have the function return a value. All values
set in the function will be destroyed when the
function is done - you must return something and
the caller must assign the return value to a variable
if you want to keep it.
E.g.,
raiz
function (f, a, b, e)
{
i <- 0
repeat {
if (i > 50) {
break
}
if (abs(a - b) < e) {
m = (a + b)/2
raiz1 = m
}
if (abs(a - b) > e) {
m = (a + b)/2
af = f(a)
if ((af * f(m)) > 0) {
a = m
}
if ((af * f(m)) < 0) {
b = m
}
}
i = i + 1
}
c(a, b) # bounds on estimate of root
}
> z <- raiz(function(x)x^4 - 3, -2, -1, 1e-10)
> z
[1] -1.316074 -1.316074
> z^4 - 3
[1] 7.566836e-12 -5.231717e-10
Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com
> -----Original Message-----
> From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org] On Behalf
> Of Berend Hasselman
> Sent: Thursday, November 29, 2012 12:13 PM
> To: finehko
> Cc: r-help at r-project.org
> Subject: Re: [R] Help in Bissection algorithm
>
>
> On 29-11-2012, at 16:18, finehko wrote:
>
> > I'm trying to make a function witch recieves a function "f", "a" and "b", and
> > the error "e". When I run the algorithm without labeling it a function and
> > typing the values it works, but when I just try to save it in a function It
> > doesn't ' bug but don't do anything.
>
> I don't understand what you mean with this: "doesn't ' bug but don't do anything"
>
> > Here's the code, anyone know whats
> > happening?
> > raiz=function(f,a,b,e){
> > repeat{
> > if(i>50){break}
> > if(abs(a-b)<e){m=(a+b)/2
> > raiz1=m}
> > if(abs(a-b)>e){
> > m=(a+b)/2
> > af=f(a)
> > if((af*f(m))>0){a=m}
> > if((af*f(m))<0){b=m}}
> > i=i+1}}
> >
>
> Initialize i before starting the repeat loop.
> i <- 1
>
> Berend
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
More information about the R-help
mailing list