• Coding
  • R (programming language)

I'm currently writing some R for a numerical analysis course I'm taking. It beats having to bother with installing MATLAB (or even worse, writing it in C)

Here is the assignment if anyone is wondering. I've solved 1(a) and started working on 2. Here's what I wrote thus far:

1a:
total <- 0
sum <- 0
n <- 0

erf5 <- function (n) {

 
   for (j in 0:n) {
      sum <- ((-1)^j * 5^(2*j+1))/((2*j+1)*factorial(j))
      total <- total + sum
   }
   
   term <- (5^(2*n+3))/( (2*n+3)*factorial(n+1))
   total <- 2/(sqrt(pi)) *(total - term)
   
   total # return it
   
}

while ( abs(1-erf5(n))>10^-6 ) n <- n+1
"n is:"
n
2 (pre-alpha, scratch work)
##########

L <- c(0.5,0.75,1,1.25,1.5,2) # test list
f <- function(x) 1/(1+4*x^2)

neville <- function (L) {
	
x <- 5
msize <- 6 # size
Q <- matrix(0, nrow = msize, ncol=msize, byrow=FALSE, dimnames =NULL)
Q[,1] <- f(L) #fill first column with f(xn)

for (i in 1:msize)
	{
		for(j in 1:i) {	
			Q[i,j] <- ((x-L[i-j])*(Q[i,j-1])-(x-L[i])(Q[i-1,j-1]))/(L[i]-L[i-j]) #currently failing
		}
	}
"Qn,n is:"
Q[msize, msize]

}

neville(L)
Note: I didn't try to optimize anything, it's my first day of writing R and I'm not trying to be efficient. It seems that the teacher only wants the answer.
Syntax seems weird, assignment looks like a pain ... :-$
It looks like C. I like it.
Hmmm, by the looks of the syntax, it seems that there should be an alternative to the loops you're doing.
   for (j in 0:n) {
      sum <- ((-1)^j * 5^(2*j+1))/((2*j+1)*factorial(j))
      total <- total + sum
   }
Something similar to :
sum <- function(a,b) a+b
total = (0:n) |> map function(x) ((-1)^x* 5^(2*x+1))/((2*x+1)*factorial(x)) |> reduce sum
P.S.: Just checked the documentation, my interpretation can be done using the apply family in R.
Great observation xterm, I read this in the manual:
Warning: for() loops are used in R code much less often than in compiled languages. Code that takes a `whole object' view is likely to be both clearer and faster in R.
5 days later