'what is the way to solve this issue

this code in R language i am having this error: Error in seq.int(2, length(xj), 2) : wrong sign in 'by' argument In addition: Warning message: In seq.int(a, b, length.out = n + 1) : first element used of 'length.out' argument can you help me to solve it , thank you

  b=1
  a=0
  n <- c(2,4,8,16,32,64,128,256,512)
  f <- function(x) {
    return(x^3/2)
  }
h <- (b - a) / n
xj <- seq.int(a, b, length.out = n + 1)
xj <- xj[-1]
xj <- xj[-length(xj)]
approx <- (h / 3) * (f(a) + 2 * sum(f(xj[seq.int(2, length(xj), 2)])) + 4 * sum(f(xj[seq.int(1, length(xj), 2)])) + f(b))
  
  return(approx)
  
}
composite.simpson(x^3/2,0,1,n) 
r


Solution 1:[1]

beside there is an unneeded }in your code (seems you cut it out of a function?),

the error for me only appeared for n<3. Which is correct. xj is an vector with the length of n+1 Next two lines are shrinking your vector by 2. For n<3 this leads to a vector of length 1. This leads to:

seq.int(from=2,to=1,by=2)

to < from & positive by --> error

EDIT:

Looking closer your code looks like the simpson's rule implementation.

n <- c(2,4,8,16,32,64,128,256,512)


f <- function(x) {
  return(x^3/2)
}

composite.simpson <- function(f, a, b, n) {
  h <- (b - a) / n
  xj <- seq.int(from = a, to = b, length.out = n + 1)
  xj <- xj[-1]
  xj <- xj[-length(xj)]
  approx <- (h / 3) * (f(a) + 
                         2 * sum(f(xj[seq.int(from = 2, to = length(xj), by = 2)])) + 
                         4 * sum(f(xj[seq.int(from = 1, to = length(xj), by = 2)])) + 
                         f(b))
  
  return(approx)
  } 

composite.simpson(f,0,1,n) 

But still n = 2 is not going to work. As the two lines:

  xj <- xj[-1]
  xj <- xj[-length(xj)]

will bring the length of xj to 1 and thereby

2 * sum(f(xj[seq.int(from = 2, to = length(xj), by = 2)])) + 

this part becomes

2 * sum(f(xj[seq.int(from = 2 to = 1 , by = 2)]))+

which is not going to work,as from > to with positive by argument.

I also found some other implementations, which "directly" exclude n = 2 or switch to a different method (example line 70).

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1