I'm trying a problem but first I have to plot in r
(x+1)(x+2)...(x+n),
with n being a fixed integer.
Any idea how to create this routine?
Provided x is greater than -1, this might be most efficiently computed by exploiting the relationship
(x + 1)*(x + 2)* ... *(x + n) = Gamma(x+n+1) / Gamma(x+1).
Gammas are computed internally in terms of their logarithms, so use these logs in the form of lgamma:
f <- function(x, n) exp(lgamma(x+n+1) - lgamma(x+1))
A plot can then be obtained via curve, for instance, as in
curve(f(x,3), 0, pi)
You want something like this?
f <- function(x, n) {
return(prod(1/(x+(1:n))))
}
Related
Let me make my question clear because I don't know how to ask it properly (therefore I don't know if it was answered already or not), I will go through my whole problem:
There is a given function (which is the right side of an explicit first order differential equation if it matters):
f = function(t,y){
-2*y+3*t
}
Then there's a given interval from 'a' to 'b', this is the range the function is calculated in with 'n' steps, so the step size in the interval (dt) is:
dt=abs(a-b)/n
In this case 'a' is always 0 and 'b' is always positive, so 'b' is always greater than 'a' but I tried to be generic.
The initial condition:
yt0=y0
The calculation that determines the vector:
yt=vector("numeric",n)
for (i in 1:(n-1))
{
yt[1]=f(0,yt0)*dt+yt0
yt[i+1]=(f(dt*i,yt[i]))*dt+yt[i]
}
The created vector is 'n' long, but this is an approximate solution to the differential equation between the interval ranging from 'a' to 'b'. And here comes my problem:
When I try plotting it alongside the exact solution (using deSolve), it is not accurate. The values of the vector are accurate, but it does not know that these values belong to an approximate function that's between the interval range 'a' to 'b' .
That's why the graphs of the exact and approximate solution are not matching at all. I feel pretty burnt out, so I might not describe my issue properly, but is there a solution to this? To make it realise that its values are between 'a' and 'b' on the 'x' axis and not between '1' and 'n'?
I thank you all for the answers in advance!
The deSolve lines I used (regarding 'b' is greater than 'a'):
df = function(t, y, params) list(-2*y+3*t)
t = seq(a, b, length.out = n)
ddf = as.data.frame(ode(yt0, t, df, parms=NULL))
I tried to reconstruct the comparison between an "approximate" solution using a loop (that is in fact the Euler method), and a solution with package deSolve. It uses the lsoda solver by default that is more precise than Euler'S method, but it is of course also an approximation (default relative and absolute tolerance set to 1e-6).
As the question missed some concrete values and the plot functions, it was not clear where the original problem was, but the following example may help to re-formulate the question. I assume that the problem may be confusion between t (absolute time) and dt between the two approaches. Compare the lines marked as "original code" with the "suggestion":
library(deSolve)
f = function(t, y){
-2 * y + 3 * t
}
## some values
y0 <- 0.1
a <- 3
b <- 5
n <- 100
## Euler method using a loop
dt <- abs(a-b)/n
yt <- vector("numeric", n)
yt[1] <- f(0, y0) * dt + y0 # written before the loop
for (i in 1:(n-1)) {
#yt[i+1] = (f( dt * i, yt[i])) * dt + yt[i] # original code
yt[i+1] <- (f(a + dt * i, yt[i])) * dt + yt[i] # suggestion
}
## Lsoda integration wit package deSolve
df <- function(t, y, params) list(-2*y + 3*t)
t <- seq(a, b, length.out = n)
ddf = as.data.frame(ode(y0, t, df, parms=NULL))
## Plot of both solutions
plot(ddf, type="l", lwd=5, col="orange", ylab="y", las=1)
lines(t, yt, lwd=2, lty="dashed", col="blue")
legend("topleft", c("deSolve", "for loop"),
lty=c("solid", "dashed"), lwd=c(5, 2), col=c("orange", "blue"))
My problem is as it says in the title, I am trying to use the derivative (with respect to v) of the modified Bessel function of the second kind K_v(x) but with no success.
I read in one of the documentation that besselDK(v,x) would work as a derivative, apparently this is not a recognized function in R. I tried to use the expansion for the derivative, namely
besselK(v,x)*(1- (1/2v) -log(e*x/2v))
but this doesn't work to give me the correct plot as well. I am trying to plot a function which includes this.
P <- function(x) (1/2)*log(exp(1)/(2*pi*x^(2)))+(3*exp(1/x^(2))/(sqrt(2*pi*x^(2))))*besselK((1/x^(2)),1/2)*(log(exp(1)/x^(2)))
x <- seq(0.1,2,0.01)
plot(x, P(x), xlim=c(0,2), ylim=c(0,1.2), type="l")
From the code above, I get a straight line as a plot. In the correct plot, it should be a curve bending between 1 and 1.5, could someone please tell me the right way to go about it?
The derivative at nu = 1/2 is given here.
f <- function(nu,x){
besselK(x, nu)
}
library(gsl) # for expint_E1
fprime <- function(x){
sqrt(pi/2/x) * expint_E1(2*x) * exp(x)
}
nu <- 1/2
h <- 1e-6
x <- 2
(f(nu+h, x) - f(nu,x)) / h
## [1] 0.02474864
fprime(x)
## [1] 0.02474864
Considering that we have a padded matrix with window size k ready for getting smoothed using the moving average, I want to know if the filter or rollapply or other R functions I am not aware of can be used to find the moving average of a submatrix. Looking at R manuals I saw they have been used for MA in 1D but just wanted to know if they can be used for MA in 2D as well or not.
mat.pad<-function(X,k){
dims<-dim(X)
n<-dims[1]
m<-dims[2]
pad.X <- matrix(0, n + 2 * k, m + 2 * k)
pad.X[(k + 1):(n + k), (k + 1):(m + k)] <- X
return(pad.X)
}
If you are asking if a moving average can be applied to a multiple dimensional object, the answer is yes.
Example
library(zoo)
#
a <- 1:10
b <- 11:20
c <- cbind(a,b)
#
rollapply(c,
FUN = mean,
width = 3)
I feel stupid asking, but what is the intent of R's crossprod function with respect to vector inputs? I wanted to calculate the cross-product of two vectors in Euclidean space and mistakenly tried using crossprod .
One definition of the vector cross-product is N = |A|*|B|*sin(theta) where theta is the angle between the two vectors. (The direction of N is perpendicular to the A-B plane). Another way to calculate it is N = Ax*By - Ay*Bx .
base::crossprod clearly does not do this calculation, and in fact produces the vector dot-product of the two inputs sum(Ax*Bx, Ay*By).
So, I can easily write my own vectorxprod(A,B) function, but I can't figure out what crossprod is doing in general.
See also R - Compute Cross Product of Vectors (Physics)
According to the help function in R: crossprod (X,Y) = t(X)%*% Y is a faster implementation than the expression itself. It is a function of two matrices, and if you have two vectors corresponds to the dot product. #Hong-Ooi's comments explains why it is called crossproduct.
Here is a short code snippet which works whenever the cross product makes sense: the 3D version returns a vector and the 2D version returns a scalar. If you just want simple code that gives the right answer without pulling in an external library, this is all you need.
# Compute the vector cross product between x and y, and return the components
# indexed by i.
CrossProduct3D <- function(x, y, i=1:3) {
# Project inputs into 3D, since the cross product only makes sense in 3D.
To3D <- function(x) head(c(x, rep(0, 3)), 3)
x <- To3D(x)
y <- To3D(y)
# Indices should be treated cyclically (i.e., index 4 is "really" index 1, and
# so on). Index3D() lets us do that using R's convention of 1-based (rather
# than 0-based) arrays.
Index3D <- function(i) (i - 1) %% 3 + 1
# The i'th component of the cross product is:
# (x[i + 1] * y[i + 2]) - (x[i + 2] * y[i + 1])
# as long as we treat the indices cyclically.
return (x[Index3D(i + 1)] * y[Index3D(i + 2)] -
x[Index3D(i + 2)] * y[Index3D(i + 1)])
}
CrossProduct2D <- function(x, y) CrossProduct3D(x, y, i=3)
Does it work?
Let's check a random example I found online:
> CrossProduct3D(c(3, -3, 1), c(4, 9, 2)) == c(-15, -2, 39)
[1] TRUE TRUE TRUE
Looks pretty good!
Why is this better than previous answers?
It's 3D (Carl's was 2D-only).
It's simple and idiomatic.
Nicely commented and formatted; hence, easy to understand
The downside is that the number '3' is hardcoded several times. Actually, this isn't such a bad thing, since it highlights the fact that the vector cross product is purely a 3D construct. Personally, I'd recommend ditching cross products entirely and learning Geometric Algebra instead. :)
The help ?crossprod explains it quite clearly. Take linear regression for example, for a model y = XB + e you want to find X'X, the product of X transpose and X. To get that, a simple call will suffice: crossprod(X) is the same as crossprod(X,X) is the same as t(X) %*% X. Also, crossprod can be used to find the dot product of two vectors.
In response to #Bryan Hanson's request, here's some Q&D code to calculate a vector crossproduct for two vectors in the plane. It's a bit messier to calculate the general 3-space vector crossproduct, or to extend to N-space. If you need those, you'll have to go to Wikipedia :-) .
crossvec <- function(x,y){
if(length(x)!=2 |length(y)!=2) stop('bad vectors')
cv <- x[1]*y[2]-x[2]*y[1]
return(invisible(cv))
}
Here is a minimalistic implementation for 3D vectors:
vector.cross <- function(a, b) {
if(length(a)!=3 || length(b)!=3){
stop("Cross product is only defined for 3D vectors.");
}
i1 <- c(2,3,1)
i2 <- c(3,1,2)
return (a[i1]*b[i2] - a[i2]*b[i1])
}
If you want to get the scalar "cross product" of 2D vectors u and v, you can do
vector.cross(c(u,0),c(v,0))[3]
There is a useful math operations package named pracma (https://rdrr.io/rforge/pracma/api/ or CRAN https://cran.r-project.org/web/packages/pracma/index.html).
Easy to use and quick. The cross product is literally given by pracma::cross(x, y) for any two vectors.
I would like to plot an implicit function of x and y: 1 - 0.125 * y ^ 2 - x ^ 2 = 0.005
I know it can be plotted as a contour plot but have trouble with the "outer" command
in the following:
x<-seq(0.4,1.01,length=1000)
y<-seq(0,3,length=1000)
z<-outer(x,y,FUN="1-0.125*y^2-x^2=0.005")
contour(x,y,z,levels=0,drawpoints=FALSE)
I read the FAQ (7.17) regarding the "outer" command and the need to vectorize the function but am still in a quandry.
I think you're a little confused about the meaning of 'function'.
All the operations (+,-,^) in your function are vectorized so that all works just fine.
x <- seq(0.4,1.01,length=1000)
y <- seq(0,3,length=1000)
z <- outer(x,y,function(x,y) 1-0.125*y^2-x^2-0.005)
contour(x,y,z,levels=0,drawlabels=FALSE)
Or if you want a minor shortcut:
library(emdbook)
curve3d(1-0.125*y^2-x^2-0.005,
xlim=c(0.4,1.01),
ylim=c(0,3),
n=c(100,100),
sys3d="contour",drawlabels=FALSE,levels=0)
This actually is slower because it uses a for loop internally rather than outer(), so I set it to 100x100 rather than 1000x1000 (which is overkill for this example anyway), but it will work on more complex examples that can't be vectorized easily ...
plotting an implicit equation as a contour plot is overkill. You are essentially throwing away 99.99% of the computations you did.
Better way is to find the value of y for a given x that will make the equation 0. Here is the code using uniroot in base R.
R code using uniroot from base R
x = seq(0, 0.995, length = 100) # no real root above x = 0.995
root <- function(a) {
uniroot(function(x,y) 1 - 0.125 * y^2 - x^2 - 0.005, c(0, 3), x = a )$root #only care about the root
}
y <- sapply(x, root)
plot(x,y, type = "l")
Ok the c(0, 3) in the uniroot argument is the range of y values where the root lies. so for every given x value uniroot will look for a y value between 0 and 3 for a root.
R code using fsolve from pracma package
library("pracma")
x <- seq(0,0.995, length=100)
fun <- function(y) c(1 - 0.125 * y^2 - x^2 - 0.005)
y_sol <- fsolve(fun, rep(1, length(x)))$x
plot(x,y_sol, type="l")
fsolve takes in the function whose root is sought and guess values of y for every given value of x. Here we are saying that the y values lie near 1. we are giving it a guess value of 1's
uniroot wants a bound range to look for root, fsolve requires a guess where the root might be.
These are faster ways to plot implicit equations. You can then use any graph package like ggplot2/rbokeh to do the plotting.
I haven't done any benchmarks so cannot tell which one method is faster. Though for such a simple implicit function it won't matter