0% found this document useful (0 votes)
57 views5 pages

R Assignment Solutions

the solution to R assignments

Uploaded by

Animesh rathi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
57 views5 pages

R Assignment Solutions

the solution to R assignments

Uploaded by

Animesh rathi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

########1########

i=2

sumSeries=1

n=1

while (n<100) {

sumSeries=sumSeries+(1/i)

i=i+2

n=n+1

sumSeries

#########2########

sum_K=0

k=1

while(sum_K<30)

sum_K = sum_K + k

k=k+1

k-1

###########3########

sumSeries_sq=0

i=1

n=1

while (i<=99) {
sumSeries_sq = sumSeries_sq + (-1)^(n+1)*(i*i)

i=i+2

n=n+1

sumSeries_sq

###########4#########

#1 Number of Iterations

f <- function(x) x^3 -5*x + 3

secant.method <- function(f, x0, x1, tolerance = 1e-9, numbiteration = 500) {

for (i in 1:numbiteration) {

x2 <- x1 - f(x1) / ((f(x1) - f(x0)) / (x1 - x0))

if (abs(x2 - x1) < tolerance ) {

return(x2)

x0 <- x1

x1 <- x2

secant.method(f, 0.5, 2.0)

#2 Bisection Method

f <- function(x) x^3 -5*x+3

bisection <- function(f, x0, x1, num = 1000, tolerance = 1e-7) {

if (!(f(x0) < 0) && (f(x1) > 0)) {


stop('signs of f(x0) and f(x1) differ')

} else if ((f(x0) > 0) && (f(x1) < 0)) {

stop('signs of f(x0) and f(x1) differ')

for (i in 1:num) {

x2 <- (x0 + x1) / 2 # midpoint

if ((f(x2) == 0) || ((x1 - x0) / 2) < tolerance) {

return(x2)

ifelse(sign(f(x2)) == sign(f(x0)),

x0 <- x2,

x1 <- x2)

bisection(f, 1, 2)

###########5#########

x=c(5,7,11,13,17)

y=c(150,392,1452,2366,5202)

n=length(x);

xx=9; Pn=c()

for(i in 1:n){

V=1:n;N=1;D=1

for(j in V[-i]){

N=N*(xx-x[j])

D = D*(x[i]-x[j])

}
Pn[i]=(N/D)*y[i]

sum(Pn)

#############6##########

#1

#Trapezoidal

f=function(x){x/(1+x)}

trapezoid <- function(f, a, b) {

h <- b - a

fxdx <- (h / 2) * (f(a) + f(b))

return(fxdx)

trapezoid(f, 0, 1)

#Simpson's

f=function(x){x/(1+x)}

simp <- function(f, a, b) {

h <- (b - a)/6

fxdx <- (h) * (f(a) + f(b)+4 * f((a+b)/2))

return(fxdx)

simp(f, 0, 1)

#2 Composite Trapezoidal

f=function(x){x/(1+x)}
ctrapezoid <- function(f, a, b) {

h <- (b - a)/6

fxdx <- (h / 2) * (f(a) + f(b)+2*(f(a+h)+f(a+2*h)+f(a+3*h)+f(a+4*h)))

return(fxdx)

ctrapezoid(f, 0, 1)

#3 Composite Simpson's

f=function(x){x/(1+x)}

a=0; b=1; n=6

h <- (b - a)/n

x = a +c(1:n)*h

z=f(x)

z0 = z[seq(1,n-1, by = 2)]

z1 = z[seq(1,n-2, by = 2)]

fxdx <- (h/3) * (f(a) + f(b)+ 4*(sum(z1))+2*(sum(z0)))

fxdx

########7#######

#1

#I1

f=function(x){1/(1+x^2)}

a=-1

b=1

I=2*f(0)

You might also like