Sum of function values in R - r

I am trying to calculate the following ( the image says f(n) = n \sum_{i=1}^{\infty} (c(i)*(1-c(i))^n)):
where c(i) is
c <- function(i){1/i^3}
In other words, f(2) is 2*{1^(-3)(1-1^(-3))^2+2^(-3)(1-2^(-3))^2+3^(-3)(1-3^(-3))^2+4^(-3)(1-4^(-3))^2+...}.
How to write such an f function in R?
My initial attempt is:
f <- function(n){n*sum(c*(1-c)^n)}
but this is obviously wrong with error
Error in 1 - c : non-numeric argument to binary operator
Please let me know if further clarification is needed. Thanks.

Clearly, you can't get an infinite sum unless you tackle it analytically, but since we can see that it's a convergent sum, we could look at, say, the first million like this:
f <- function(n) {
C <- 1 / seq(1e6)^3
n * sum(C * (1 - C)^n)
}
Which allows:
f(1)
#> [1] 0.1847138
f(2)
#> [1] 0.3387583
f(3)
#> [1] 0.4674204
In case you are worried that this is not accurate enough, we get the same result out to 7 digits by summing only the first 10,000 terms, so 1 million should be very close to the converged value.

Related

Using mosaicCalc::D() to differentiate expression giving unexpected result

I am attempting to differentiate the expression -1+3*x^2/1+x^2 with respect to x, but the output is incorrect. The correct output should be:
8x/(1+x^2)^2
#> library(mosaicCalc)
#>
#> l=D(-1+3*x^2/1+x^2 ~x)
#> l
function (x)
8 * x
Edit:
I have used parenthesis, but the output is still incorrect
#> t=D((-1+3*x^2)/1+x^2 ~x)
#> t
function (x)
8 * x
Furthermore, I have used parenthesis for both the numerator and the denominator, and the output for the second derivative is incorrect.
> b = D((-1+3*x^2)/(1+x^2) ~x)
> b
function (x)
{
.e1 <- x^2
.e2 <- 1 + .e1
x * (6 - 2 * ((3 * .e1 - 1)/.e2))/.e2
}
> k = D(b~ x)
> k
function (x, t)
0
The correct answer for the second derivative is 8(-3x^2+1)/(1+x^2)^3
https://www.symbolab.com/solver/step-by-step/%5Cfrac%7Bd%7D%7Bdx%7D%5Cfrac%7B8x%7D%7B%5Cleft(1%2Bx%5E%7B2%7D%5Cright)%5E%7B2%7D%7D?or=input
I think you need b(x) ~ x to get your second derivative. That will give you an expression in x that can be differentiated. As is, you are differentiating an expression that doesn’t depend on x, so the derivative is 0.
I might create an issue on GitHub to see if it is possible to emit a useful message in this case.

How to make a function that sums the exponential's of a vector in R?

My professor has assigned a question for programming in R and I am stuck. He wants us to make a function that will take the exponential (e^(x[i]) of all the numbers in a vector and then sum them. the equation is:
the summation of e^x(i), n, and i=1.
I have made a function that will give me the exponential of the first value in my vector. But I want to get the exponential of all the values and sum them. Here is my code
#Vector for summing
x=c(2,1,3,0.4)
#Code for function
mysum = 0
myfun=function(x){
for (i in 1:length(x)){
mysum = mysum + exp(x[i])
return(mysum)
}
}
myfun(x)
#returns 7.389056
I have also tried using i = 1:1 because the equation specifies i=1, even though I knew that would only go through 1 number, and it gave me the same answer.... obviously.
myfun=function(x){
for (i in 1:1)
Does anyone have any suggestions to get it to sum?
You need to set the initial value of mysum to the accumulation afterwards, and also move the line return(mysum) outsides your for loop to return the result, i.e.,
myfun=function(x){
mysum <- 0
for (i in 1:length(x)){
mysum = mysum + exp(x[i])
}
return(mysum)
}
or just
myfun=function(x){
mysum <- 0
for (i in x){
mysum = mysum + exp(x)
}
return(mysum)
}
Since exp operation is vectoroized, you can also define your function myfun like below
myfun <- function(x) sum(exp(x))
You could also use the fact that most base functions are already vectorized :
1) create a dummy vector
1:10
#> [1] 1 2 3 4 5 6 7 8 9 10
2) apply your function on that vector, you get vectorized result
exp(1:10)
#> [1] 2.718282 7.389056 20.085537 54.598150 148.413159
#> [6] 403.428793 1096.633158 2980.957987 8103.083928 22026.465795
3) Sum that vector
sum(exp(1:10))
#> [1] 34843.77
4) Write your function to gain (a little) time
my_fun <- function(x){sum(exp(x))}
my_fun(1:10)
#> [1] 34843.77

What does rpois() do in the following case?

rpois() takes two values (n, and lambda) to generate n random numbers according to Poisson distribution.
But, what is rpois() doing in the following case?
> n = c(0,1,2,3,4,5,6,7,8,9)
> lamda = 10
> rpois(n, lamda)
[1] 13 15 10 9 10 11 10 10 11 15
>
from the docs:
The length of the result is determined by ‘n’ for ‘rpois’, and is
the maximum of the lengths of the numerical arguments for the
other functions.
it's therefore the same as:
rpois(length(n), lambda)
a bit more digging, it ends up calling do_random1 in src/main/random.c. which basically says:
if (length(param1) == 1) {
n = as.integer(param1)
} else {
n = length(param1)
}
but in C, and with fiddling to make sure it works with "long" vectors, etc.

Solving a system of nonlinear equations in R

Suppose I have the following system of equations:
a * b = 5
sqrt(a * b^2) = 10
How can I solve these equations for a and b in R ?
I guess this problem can be stated as an optimisation problem, with the following function... ?
fn <- function(a, b) {
rate <- a * b
shape <- sqrt(a * b^2)
return(c(rate, shape) )
}
In a comment the poster specifically asks about using solve and optim so we show how to solve this (1) by hand, (2) using solve, (3) using optim and (4) a fixed point iteration.
1) by hand First note that if we write a = 5/b based on the first equation and substitute that into the second equation we get sqrt(5/b * b^2) = sqrt(5 * b) = 10 so b = 20 and a = 0.25.
2) solve Regarding the use of solve these equations can be transformed into linear form by taking the log of both sides giving:
log(a) + log(b) = log(5)
0.5 * (loga + 2 * log(b)) = log(10)
which can be expressed as:
m <- matrix(c(1, .5, 1, 1), 2)
exp(solve(m, log(c(5, 10))))
## [1] 0.25 20.00
3) optim Using optim we can write this where fn is from the question. fn2 is formed by subtracting off the RHS of the equations and using crossprod to form the sum of squares.
fn2 <- function(x) crossprod( fn(x[1], x[2]) - c(5, 10))
optim(c(1, 1), fn2)
giving:
$par
[1] 0.2500805 19.9958117
$value
[1] 5.51508e-07
$counts
function gradient
97 NA
$convergence
[1] 0
$message
NULL
4) fixed point For this one rewrite the equations in a fixed point form, i.e. in the form c(a, b) = f(c(a, b)) and then iterate. In general, there will be several ways to do this and not all of them will converge but in this case this seems to work. We use starting values of 1 for both a and b and divide both side of the first equation by b to get the first equation in fixed point form and we divide both sides of the second equation by sqrt(a) to get the second equation in fixed point form:
a <- b <- 1 # starting values
for(i in 1:100) {
a = 5 / b
b = 10 / sqrt(a)
}
data.frame(a, b)
## a b
## 1 0.25 20
Use this library.
library("nleqslv")
You need to define the multivariate function you want to solve for.
fn <- function(x) {
rate <- x[1] * x[2] - 5
shape <- sqrt(x[1] * x[2]^2) - 10
return(c(rate, shape))
}
Then you're good to go.
nleqslv(c(1,5), fn)
Always look at the detailed results. Numerical calculations can be tricky. In this case I got this:
Warning message:
In sqrt(x[1] * x[2]^2) : NaNs produced
That just means the procedure searched a region that included x[1] < 0 and then presumably noped the heck back to the right hand side of the plane.

Plotting a constant function in R with curve()

so I have an error...
f <- function(x){return(1)}
curve(f(x),0,100,xname="x")
Error in curve(f(x), 0, 100, xname = "x") :
'expr' did not evaluate to an object of length 'n'
Which is strange considering that
F <- function(x){return(0*x+1)}
curve(F(x),0,100,xname="x")
Works just fine... This informed me to think about how R treats data.frame()s.
a <- data.frame(1,2,3)
f(a)
# [1] 1
F(a)
# X1 X2 X3
# 1 1 1 1
Meaning that the Function Vectorize() will fix my problem.
Irregardless this is an acute example of the implicit decisions That R makes, which result in inconsistent behavior.
The problem is the function should return a vector of the same length as a parameter. In your case instead of n, the function always returns a vector of just one. The solution could be
f <- function(x){return(rep(1,length(x)))}

Resources