forecaster
forecaster

Reputation: 1159

do until loop logic in R

I have a function fk, I have another function calc where I pass 2 values x and y. I wanted to do the following, until fk(x)*fk(y) <0, I want to double the interval (y-x). How would I accomplish this in R. I'm struggling on logic, any help would be greatly appreciated,

fk <- function(x) {
    return((x*x)-(3*x)+4)
}

calc <- function(x,y) {  
    g <- fk(x)*fk(y)

    until g < 0 do 
    double the interval (y-x)
}

Upvotes: 3

Views: 3258

Answers (2)

Paulo MiraMor
Paulo MiraMor

Reputation: 1610

You could do that using while:

while (fk(x) * fk(y) < 0) {
    interval <- (y-x) * 2
}

Your function would look like:

calc <- function(x,y) {  

 while (fk(x) * fk(y) < 0) {
        interval <- (y-x) * 2
    }
}

Upvotes: 2

Tim Biegeleisen
Tim Biegeleisen

Reputation: 522719

You want to use something along these lines:

calc <- function(x,y) { 
    while (TRUE) {
        g <- fk(x)*fk(y)
        if (g < 0) {
            break
        }
        // otherwise double interval (y-x)
    }
}

As I mentioned in my comment, it is not clear how you want to adjust the values for x and y in order to "double" the interval. Once you figure that out, you can add the required code to the loop.

Upvotes: 2

Related Questions