Generating my own arbitrary polynomials in Julia - julia

I have a problem where I need to generate my own monomial sequence of N terms and evaluate it numerically - a polynomial basis, mind you.
What I need is a function that I can generate. The problem is that (as far as I know) I can't iterate over a function I have already defined in order to keep adding terms of my own devising (the monomials), which is what I want. The only way I know how to add the terms that I want is manually, but that won't do.
Basically, I want something like...
N=4
#Code runs, and then I get something like the following:
f(x) = x^0 + c1*x + c2*x^2 + c3*x^3 + c4*x^4
And I want it to be a function that can be evaluated or differentiated via other packages.
Note: I want to operate on the coefficients in order to see if I can solve a problem where I assume the polynomial is the solution that I then have to optimize.
Yes, I know the package Polynomials.jl can tackle the aforementioned example quite readily and cleanly, but what I want is to be able to define each of the terms that I keep adding to the polynomial sequence myself, make them a trigonimetric function, an exponential, etc. Maybe I want to define the Fourier series, or whatever. I want to build my own polynomial base that I can then evaluate.
Like this:
N=4
#Code runs, and then I get the following:
f(x) = x^0 + c1*cos(x) + c2*sin(x) + c3*exp(3*x) + c4*x^4
I tried with Symbolics.jl, played with Polynomials.jl, tried to get it done with varargs, and nothing worked. I am genuinely stumped. Any help would be greatly appreciated, even if just to tell me "Go learn metaprogramming," or something like that.

Maybe this can help or at least gives you an insight:
julia> function myf(x, coefs)
myExpressions = [x^0, cos(x), sin(x), exp(3*x), x^4]
#assert length(coefs) == length(myExpressions) "The length of coefficients doesn't match the length of the expressions."
return coefs*myExpressions
end
julia> myf(1, [1 2 3 4 5])
1-element Vector{Float64}:
89.94716525891064
julia> myf(1, [1 2 3 4])
ERROR: AssertionError: The length of coefficients doesn't match the length of the expressions.

Related

Sigma Notation in Julia

I am having trouble understanding how to solve summation notation in Julia. I have the parts in parenthesis figured out, but do not know how to calculate the summation part. My problem looks something like this:
100
∑ (4n^x + 4/n)
n=1
Is there a built in function or a way for me to code the summation part?
One example:
f(x) = sum(4n^x + 4/n for n in 1:100)

How can I resolve an exponential function for x in R?

I want to analyse a logarithmic growth curve in more detail. Especially I would like to kow the time point when the slope becomes >0 (which is the starting point of growth after a lag phase).
Therefore I fitted a logarithmic function to my growth data with the grofit package of R. I got values for the three parameters (lambda, mu, maximal assymptote).
Now I thought, I could use the first derivative of the logarithmic growth function to put mu=0 (the slope of any time point during growth) and this way solve the equation for the time (x). I'm not sure if this is possible, since the mu=0 will be correct for a longer timespan at the beginning of the curve (and no unique timepoint). But maybe I could approximate to that point by putting mu=0.01. This should be more specific.
Anyway I used the Deriv package to find the first derivative of my logarithmic function:
Deriv(a/(1+exp(((4*b)/a)*(c-x)+2)), "x")
where a=assymptote, b=maximal slope, c=lambda.
As a result I got:
{.e2 <- exp(2 + 4 * (b * (c - x)/a))
4 * (.e2 * b/(.e2 + 1)^2)}
Or in normal writing:
f'(x)=(4*exp(2+((4b(c-x))/a))*b)/((exp(2+((4b(c-x))/a))+1)^2)
Now I would like to solve this function for x with f'(x)=0.01. Can anyone tell me, how best to do it?
Also, do you have comments on my way of thinking or the R functions I used?
Thank you.
Anne
Using a root solving function is more appropriate than using an optimization function.
I'll give an example with two packages.
It would also be a good idea to plot the function for a range of values.
Like this:
curve(fn,-.1,.1)
You can see that using the base R function uniroot will present problems since it needs function values at the endpoints of the interval to be of opposite sign.
Using package nleqslv like this
library(nleqslv)
nleqslv(1,fn)
gives
$x
[1] 0.003388598
$fvec
[1] 8.293101e-10
$termcd
[1] 1
$message
[1] "Function criterion near zero"
<more info> ......
Using function fsolve from package pracma
library(pracma)
fsolve(fn,1)
gives
$x
[1] 0.003388585
$fval
[1] 3.136539e-10
The solutions given by both packages are very close to each other.
Might not be the best approach but you can use the optim function to find the solution. Check the code below, I am basically trying to find the value of x which minimizes abs(f(x) - 0.01)
There starting seed value for x may be important, the optim function might not converge for some seeds.
fn <- function(x){
a <- 1
b<- 1
c <- 1
return( abs((4*exp(2+((4*b*(c-x))/a))*b)/ ((exp(2+((4*b*(c-x))/a))+1)^2) - 0.01) )
}
x <- optim(10,fn)
x$par
Thank you very much for your efforts. Unfortunately, none of the above solutions worked for me :-(
I figured the problem out the old fashioned way (pencil + paper + mathematics book).
Have a good day
Anne

How to have sigma of something while plotting?

I am using plotFun function of mosaic package in R. I am trying to plot a 3D plot. Following is my code snippet:
plotFun(2*l*(w/log(beta*kspill*lambda^2+(1+(w/x-w)/10)*(lambda^2*5+lambda^1*5+1))+(w/x-w)/log((1+((w/x-w)/10)^1)*(lambda^2*5+lambda^1*5+1))) ~ x & lambda ,
x.lim=range(0.8,1), lambda.lim=range(1,3),
l=60,w=40,kspill=10,f=1,beta=0.5,surface=TRUE)
This is working fine. Now suppose I want to fix lambda and introduce a new variable t such that if t=2 we get lambda^2*5+lambda^1*5+1 as in the above case. If t=3 we get lambda^3*5+lambda^2*5+lambda^1*5+1 and so on. So now I have t.lim=range(1,3) for a fixed lambda :
plotFun(2*l*(w/log(beta*kspill*lambda^2+(1+(w/x-w)/10)*("depends on t"))+(w/x-w)/log((1+((w/x-w)/10)^1)*("depends on t"))) ~ x & lambda ,
x.lim=range(0.8,1), t.lim=range(0.5,1),
l=60,w=40,kspill=10,f=1,beta=0.5,lambda=1,surface=TRUE)
What to write in the "depends on t" part above. I guess we can't put a for loop there to calculate 5* {summation i=0 to i=t}lambdai. How to go about doing this?
You can define your "depends on t" with
depends_on_t <- makeFun(5 * sum(lambda^(1:round(t))) + 1 ~ t + lambda, lambda = 1)
But you still have some issues to resolve:
1) Your plotFun() command is creating a plot using x and lambda, but I'm guessing you meant x and t.
2) t can only be an integer if you are going to use it in a sum of the type you are suggesting. But you are creating a plot that assumes continuous variables for the axes. I inserted round(t) as one way to move from real values to integer values before computing the sum. The makes the function work for non-integer values, but it might not be what you really want.
Finally, some additional suggestions:
3) x & lambda should be replaced with x + lambda. The use of & here dates back to the very early days of the mosaic package, and although it is still supported (I think, we don't really test for it anymore), we prefer x + lambda.
4) I recommend separating out the definition of your function from the plotFun() command. You can use mosaic::makeFun() as illustrated above, or the usual function() to define your function and whatever default values you want for its arguments. Then you can do sanity checks on the function, or use it in multiple plots rather than including all of the function's definition in each plot.
5) Using spaces and returns would make your code much more readable. (As would simplifying your example to a minimal example that demonstrates the issue you are asking about.)
6) I think you might want
depends_on_t <- makeFun(5 * sum(lambda^(0:round(t))) ~ t + lambda, lambda = 1)
rather than the formula as you describe it, but without more context, I can't really know.

How to simplify or rearrange an equation to a specific form in mathematica

I have an equation:
Y[u_, v_, w_]:=(sin[u] + v*cos[u]*sin[u - w] - v*sin[w])
Which needs to be expressed in a specific form:
Y[u_, v_, w_]:=(a*sin[u] + b*sin[2*u] + c*cos[2*u] + d*v*sin[w])
From doing this by hand, I happen to know that:
a=1
b=(v*cos[w]/2)
c=-(v*sin[w]/2)
d=-(3/2)
This particular example is easy to do by hand with trig identities, but for more complicated equations, mathematica could be very useful if the final form of the equation is known. Is there some specific solver function, or a way to use Solve to do this?
For my particular application with a more complicated equation, I have found a few coefficients of the final form by hand, but others are very long and I would like to use mathematica to both check, and finish the rearrangement.
Trying to get Mathematica to put an expression into exactly the form you want is often very difficult to do.
You might consider this method of checking your calculations
In[1]:= expr = (Sin[u] + v*Cos[u]*Sin[u - w] - v*Sin[w]);
{ Integrate[expr*Sin[u], {u, 0, 2 Pi}]/Pi,
Integrate[expr*Sin[2*u], {u, 0, 2 Pi}]/Pi,
Integrate[expr*Cos[2*u], {u, 0, 2 Pi}]/Pi,
Integrate[expr*v*Sin[w], {w, 0, 2 Pi}]/Pi}
Out[1]= {1, 1/2 v Cos[w], -(1/2) v Sin[w], -v^2 (1 + Cos[u]^2)}
What that is doing is the equivalent of finding the Fourier transform of your expression for a single frequency u, or w in the case of d. In your example it correctly finds the values of a, b and c, but fails in finding d. Unfortunately I can't see at the moment exactly why it is failing for d, but perhaps someone with a clear head can point out what the error is.
Be careful with this, as you see, don't just assume the result will always be correct. I am worried for your much more complicated actual problem this may not give you what you are looking for.

troubles with integration on matlab

I'd like some help please I really need to solve this problem.
Well before anything thank you for your time...
My problem: I have a matrix (826x826 double) and I want to integrate this matrix with respect to a vector of (826x1 double) I don't have the functions of any of this. Is there a command or an algorithm to take the integral of a matrix with respect to a vector? Please I really need help, I'm such a newbie at matlab.
Sincerely.
George
If it's a constant matrix A integrated with respect to vector x, your answer in simply Ax + c where c is some constant vector. If A is a function of x, you will need to specify exactly what it is. Another case is when both A and x are functions of t. There is no one simple answer and no computer program would do it in most cases. There are books written in this stuff. It's not an easy task.
If I understand correctly, you have a matrix Y (size mxn) and a vector X (size mx1) where Y(i, j) = f_j(X(i)) for some unknown function f_j. To approximate the integral of each column over X you could use the trapz function of Matlab which uses the trapezoidal method.
A = trapz(X, Y);
This will integrate Y along its columns using the vector X. If you wanted to integrate along rows you can call the trapz function with an added argument of dim=2. Of course, the dimensions of X and Y must be compatible in either case.

Resources