#import math # Don't need to import anything yet, but in R the command is library #def fun(x): # return x+math.sin(2**x) # in python need ** instead ^ fun <- function(x){ x+sin(2^x) # R functions return the last computed thing # R has some trig preloaded and is OK with ^ } #from scipy.integrate import quad #R already has integrate preloaded a <- -1 # <- instead of = b <- 2 bubba <- integrate(fun,lower=a,upper=b) # first element is integral estimate, second element is # an estimate of an upper bound on the error # intV = quad(fun,a,b)[0] # errV = quad(fun,a,b)[1] #print(intV) print(bubba) intV <- bubba$value #this is like a data frame with column name 'value' N <- c(2,4,8,16,32,64) # instead of [2,4,8,16,32,64] left <- c() right <- c() trap <- c() simp <- c() #exact = [intV for n in N] # list comprehension does not work easily in R exact <- c() for (j in N){ exact <- c(exact, intV) } #for n in N: #h = (b-a)/n #x = [a+j*h for j in range(n+1)] #y = [fun(bubba) for bubba in x] #left += [h*sum(y[:-1])] # y[:-1] means all indices up through the 2nd last index ## y[A:B] means indices A through B-1. #right += [h*sum(y[1:])] #trap += [h/2*(y[0]+y[-1]+2*sum(y[1:-1]))] # note y[1:-1]=y[1:n] #simp += [h/3*(y[0]+y[-1]+4*sum(y[1:-1:2])+2*sum(y[2:-1:2]))] ##y[1:-1:2] means indices 1,3,5,...,stop before the last # for (n in N){ h <- (b-a)/n x <- c() for (j in 0:n){ # in R, 2:7 means 2 3 4 5 6 7 x <- c(x,a+j*h) } y <- c() for (xx in x){ y <- c(y,fun(xx)) } } y