Defining a function on an interval - wolfram-mathematica

Fairly basic question, but one I can't seem to find an answer to- How can I define a function f(x) on an x interval [0, 10]?

There are almost always several different ways of writing anything using Mathematica.
One way is:
f[x_]:=Piecewise[{{x^2,0<=x<=10}}]
which will have the value x^2 over [0,10] and 0 elsewhere. You can look at the documentation for Piecewise and see how you can change the value elsewhere.
Another way is
f[x_/;0<=x<=10]:=x^2
which will have the value x^2 over [0,10] and f[x] elsewhere. You can look at the documentation for /; (also called Condition) and see how that is define.
Another way is
f[x_]:=If[0<=x<=10,x^2]

Related

How to find inverse function in Wolfram Mathematica?

The question seems too easy to answer, however it is not, since I have to deal with functions that do not have closed forms (or I don't know how to find them). For example, I would like to find inverse functions for:
y == x Tan[x]
and
y == a x + b Tan[x].
Thus far, I used Newton-Rhapson's method for the inverse transformations. It works fine, but requires iterations. I just wonder whether there is a method to prove that there is a better solution or not. I've tried Wolfram Mathematica to find a solution, but since I'm a beginner. I have had no luck to get anything meaningful.
Seems it can't be done.
Solve[y == x Tan[x], x]
Solve::nsmet: This system cannot be solved with the methods available to Solve.
InverseFunction[# Tan[#] &]

Working with real functions in mathematica

In general, mathematica always assumes the most general case, that is, if I set a function
a[s_]:={a1[s],a2[s],a3[s]}
and want to compute its norm Norm[a[s]], for example, it will return:
Sqrt[Abs[a1[s]]^2 + Abs[a2[s]]^2 + Abs[a3[s]]^2]
However, if I know that all ai[s] are real, I can invoke:
Assuming[{a1[s], a2[s], a3[s]} \[Element] Reals, Simplify[Norm[a[s]]]]
which will return:
Sqrt[a1[s]^2 + a2[s]^2 + a3[s]^2]
Which is what I expect.
Problem happens when trying to, for example, derive a[s] and then (note the D):
Assuming[{a1[s], a2[s], a3[s]} \[Element] Reals, Simplify[Norm[D[a[s],s]]]]
Returns again a result involving absolute values - coming from the assumption that the numbers may be imaginary.
What is the way to overcome this problem? I want to define a real-valued function, and work with it as such. That is, for instance, I want its derivatives to be real.
I would use a custom function instead, e.g.
vecNorm[vec_?VectorQ] := Sqrt[ vec.vec ]
Then
In[20]:= vecNorm[D[{a1[s], a2[s], a3[s]}, s]]
Out[20]= Sqrt[
Derivative[1][a1][s]^2 + Derivative[1][a2][s]^2 +
Derivative[1][a3][s]^2]
Warning: I don't have much practical experience with this, so the examples below are not thoroughly tested (i.e. I don't know if too general assumptions can break anything I haven't thought of).
You can use $Assumptions to define permanent assumptions:
We could say that all of a1[s], a2[s], a3[s] are reals:
$Assumptions = {(a1[s] | a2[s] | a3[s]) \[Element] Reals}
But if you have e.g. a1[x] (not a1[s]), then it won't work. So we can improve it a bit using patterns:
$Assumptions = {(a1[_] | a2[_] | a3[_]) \[Element] Reals}
Or just say that all values of a[_] are real:
$Assumptions = {a[_] \[Element] Reals}
Or even be bold and say that everything is real:
$Assumptions = {_ \[Element] Reals}
(I wonder what this breaks)
AppendTo is useful for adding to $Assumptions and keeping previous assumptions.
Just like Assuming, this will only work for functions like Simplify or Integrate that have an Assumtpions option. D is not such a function.
Some functions like Reduce, FindInstance, etc. have an option to work only on the domain of Reals, Integers, etc., which assumes that all expressions and subexpressions they work with are real.
ComplexExpand[] and sometimes FunctionExpand[] may also be useful in similar situations (but not really here). Examples: ComplexExpand[Abs[z]^2, TargetFunctions -> {Sign}] and FunctionExpand[Abs'[x], Assumptions -> {x \[Element] Reals}].
Generally, as far as I know, there is no mathematical way to tell Mathematica that a variable is real. It is only possible to do this in a formal way, using patterns, and only for certain functions that have the Assumptions option. By "formal" I mean that if you tell it that a[x] is real, it will not know automatically that a'[x] is also real.
You could use ComplexExpand in this case albeit with a workaround. For example
ComplexExpand[Norm[a'[s], t]] /. t -> 2
returns
Sqrt[Derivative[1][a1][s]^2 + Derivative[1][a2][s]^2 + Derivative[1][a3][s]^2]
Note that doing something like ComplexExpand[Norm[a'[s], 2]] (or indeed ComplexExpand[Norm[a'[s], p]] where p is a rational number) doesn't work for some reason.
For older Mathematica versions there used to be an add-on package RealOnly that put Mathematica in a reals-only mode. There is a version available in later versions and online with minimal compatibility upgrades. It reduces many situations to a real-only solution, but doesn't work for your Norm case:

What does // mean in Mathematica?

Examples:
In
CT = Table[Prepend[10^4*x[range2] /.
NDSolve[{...series of equations here...}, {t, range1, range2},
MaxSteps -> 10000,
PrecisionGoal -> 11], delay],
{delay, delaymin, delaymax, 0.1}]; // Timing
what does it mean this // Timing after the semicolon?
In
Dρ = -I*((H0 + V).ρ - ρ.(H0 + V)) - Γ*ρ // Simplify;
And this // Simplify here?
I can't find this explanation anywhere!
Thanks in advance,
Thiago
This is Mathematica's postfix notation.
Basically x//f is the same as f[x]
Yes, argument // function is postfix function application.
Useful about it is that it has a different, lower binding power relative to prefix application (f # x).
In fact it is lower than most other things (exceptions include CompoundExpression ; and Set =), and therefore it can often be considered as "apply to everything before this."
You say: "I can't find this explanation anywhere!". I assume this means you are not aware of the documentation center that's right under your fingertips whenever you're using Mathematica.
All you have to do is to place your cursor on the // and press F1 and you'll get some sort of explanation, or a list with relevant (hopefully) matches. In this case the PostFix page, which is not extremely helpful. However, it has some links at the bottom (assuming you have versions 6, 7 or 8) that provide more insight, among which a link to the syntax overview page (click the Mathematica syntax link, or enter "guide/Syntax" in the search box).
expr // f is essentially equivalent to f[expr]. Sometimes, it's called postfix notation. I read expr // f as "pass the expression expr to the function f".
a // f
is, I believe, the same thing as
f[a]
(which incidentally, any sane mathematician I know would write as
f(a)
just as it is done in most computer languages.)
As others have mentioned, // is the postfix notation and expr//f means f[expr] in mathematica and f(expr) in math.
Although there might be more subtleties involved, my usage of // has often been in cases where I've started writing out an expression and then realized I wanted to operate a function on it. So instead of moving the cursor all the way back to type f#expr or f[expr], I can simply finish typing what I had in mind, and use expr//f.
Example:
Plot[Sin[x],{x,0,Pi}]
%//Export["test.pdf",#]&
The graphics is passed to the export function and is saved as test.pdf.
As your question has already got very good answers, I want to add just a clarification on usage.
The three expressions
Sin[x]
Sin#x
x // Sin
Are equivalent.
Although, to my knowledge, the last two can't be used with functions with more than one argument. So
Plot[Sin[x], {x, 0, Pi}]
Can't be invoked in prefix or postfix notation without tricks like
Sin[x] // Plot[#, {x, 0, Pi}] &
or
Plot[#, {x, 0, Pi}] &#Sin[x]
The prefix notation is usually seen when using simple functions like Sin#x or Sort#list, while most uses of the postfix involve a reasoning like "and now do whatever with this thing I got", for example
(Sin#x+ ...) // Timing
where you decided what to calculate, and then you also want it timed.
One more note:
Really there is much more under the scenes, as the priority of each of these functional constructs is different, but I think that is a much deeper subject and you have to experiment a little before going for subtleties.

Iterative solving for unknowns in a fluids problem

I am a Mechanical engineer with a computer scientist question. This is an example of what the equations I'm working with are like:
x = √((y-z)×2/r)
z = f×(L/D)×(x/2g)
f = something crazy with x in it
etc…(there are more equations with x in it)
The situation is this:
I need r to find x, but I need x to find z. I also need x to find f which is a part of finding z. So I guess a value for x, and then I use that value to find r and f. Then I go back and use the value I found for r and f to find x. I keep doing this until the guess and the calculated are the same.
My question is:
How do I get the computer to do this? I've been using mathcad, but an example in another language like C++ is fine.
The very first thing you should do faced with iterative algorithms is write down on paper the sequence that will result from your idea:
Eg.:
x_0 = ..., f_0 = ..., r_0 = ...
x_1 = ..., f_1 = ..., r_1 = ...
...
x_n = ..., f_n = ..., r_n = ...
Now, you have an idea of what you should implement (even if you don't know how). If you don't manage to find a closed form expression for one of the x_i, r_i or whatever_i, you will need to solve one dimensional equations numerically. This will imply more work.
Now, for the implementation part, if you never wrote a program, you should seriously ask someone live who can help you (or hire an intern and have him write the code). We cannot help you beginning from scratch with, eg. C programming, but we are willing to help you with specific problems which should arise when you write the program.
Please note that your algorithm is not guaranteed to converge, even if you strongly think there is a unique solution. Solving non linear equations is a difficult subject.
It appears that mathcad has many abstractions for iterative algorithms without the need to actually implement them directly using a "lower level" language. Perhaps this question is better suited for the mathcad forums at:
http://communities.ptc.com/index.jspa
If you are using Mathcad, it has the functionality built in. It is called solve block.
Start with the keyword "given"
Given
define the guess values for all unknowns
x:=2
f:=3
r:=2
...
define your constraints
x = √((y-z)×2/r)
z = f×(L/D)×(x/2g)
f = something crazy with x in it
etc…(there are more equations with x in it)
calculate the solution
find(x, y, z, r, ...)=
Check Mathcad help or Quicksheets for examples of the exact syntax.
The simple answer to your question is this pseudo-code:
X = startingX;
lastF = Infinity;
F = 0;
tolerance = 1e-10;
while ((lastF - F)^2 > tolerance)
{
lastF = F;
X = ?;
R = ?;
F = FunctionOf(X,R);
}
This may not do what you expect at all. It may give a valid but nonsense answer or it may loop endlessly between alternate wrong answers.
This is standard substitution to convergence. There are more advanced techniques like DIIS but I'm not sure you want to go there. I found this article while figuring out if I want to go there.
In general, it really pays to think about how you can transform your problem into an easier problem.
In my experience it is better to pose your problem as a univariate bounded root-finding problem and use Brent's Method if you can
Next worst option is multivariate minimization with something like BFGS.
Iterative solutions are horrible, but are more easily solved once you think of them as X2 = f(X1) where X is the input vector and you're trying to reduce the difference between X1 and X2.
As the commenters have noted, the mathematical aspects of your question are beyond the scope of the help you can expect here, and are even beyond the help you could be offered based on the detail you posted.
However, I think that even if you understood the mathematics thoroughly there are computer science aspects to your question that should be addressed.
When you write your code, try to make organize it into functions that depend only upon the parameters you are passing in to a subroutine. So write a subroutine that takes in values for y, z, and r and returns you x. Make another that takes in f,L,D,G and returns z. Now you have testable routines that you can check to make sure they are computing correctly. Check the input values to your routines in the routines - for instance in computing x you will get a divide by 0 error if you pass in a 0 for r. Think about how you want to handle this.
If you are going to solve this problem interatively you will need a method that will decide, based on the results of one iteration, what the values for the next iteration will be. This also should be encapsulated within a subroutine. Now if you are using a language that allows only one value to be returned from a subroutine (which is most common computation languages C, C++, Java, C#) you need to package up all your variables into some kind of data structure to return them. You could use an array of reals or doubles, but it would be nicer to choose to make an object and then you can reference the variables by their name and not their position (less chance of error).
Another aspect of iteration is knowing when to stop. Certainly you'll do so when you get a solution that converges. Make this decision into another subroutine. Now when you need to change the convergence criteria there is only one place in the code to go to. But you need to consider other reasons for stopping - what do you do if your solution starts diverging instead of converging? How many iterations will you allow the run to go before giving up?
Another aspect of iteration of a computer is round-off error. Mathematically 10^40/10^38 is 100. Mathematically 10^20 + 1 > 10^20. These statements are not true in most computations. Your calculations may need to take this into account or you will end up with numbers that are garbage. This is an example of a cross-cutting concern that does not lend itself to encapsulation in a subroutine.
I would suggest that you go look at the Python language, and the pythonxy.com extensions. There are people in the associated forums that would be a good resource for helping you learn how to do iterative solving of a system of equations.

Is there a way to predict unknown function value based on its previous values

I have values returned by unknown function like for example
# this is an easy case - parabolic function
# but in my case function is realy unknown as it is connected to process execution time
[0, 1, 4, 9]
is there a way to predict next value?
Not necessarily. Your "parabolic function" might be implemented like this:
def mindscrew
#nums ||= [0, 1, 4, 9, "cat", "dog", "cheese"]
#nums.pop
end
You can take a guess, but to predict with certainty is impossible.
You can try using neural networks approach. There are pretty many articles you can find by Google query "neural network function approximation". Many books are also available, e.g. this one.
If you just want data points
Extrapolation of data outside of known points can be estimated, but you need to accept the potential differences are much larger than with interpolation of data between known points. Strictly, both can be arbitrarily inaccurate, as the function could do anything crazy between the known points, even if it is a well-behaved continuous function. And if it isn't well-behaved, all bets are already off ;-p
There are a number of mathematical approaches to this (that have direct application to computer science) - anything from simple linear algebra to things like cubic splines; and everything in between.
If you want the function
Getting esoteric; another interesting model here is genetic programming; by evolving an expression over the known data points it is possible to find a suitably-close approximation. Sometimes it works; sometimes it doesn't. Not the language you were looking for, but Jason Bock shows some C# code that does this in .NET 3.5, here: Evolving LINQ Expressions.
I happen to have his code "to hand" (I've used it in some presentations); with something like a => a * a it will find it almost instantly, but it should (in theory) be able to find virtually any method - but without any defined maximum run length ;-p It is also possible to get into a dead end (evolutionary speaking) where you simply never recover...
Use the Wolfram Alpha API :)
Yes. Maybe.
If you have some input and output values, i.e. in your case [0,1,2,3] and [0,1,4,9], you could use response surfaces (basicly function fitting i believe) to 'guess' the actual function (in your case f(x)=x^2). If you let your guessing function be f(x)=c1*x+c2*x^2+c3 there are algorithms that will determine that c1=0, c2=1 and c3=0 given your input and output and given the resulting function you can predict the next value.
Note that most other answers to this question are valid as well. I am just assuming that you want to fit some function to data. In other words, I find your question quite vague, please try to pose your questions as complete as possible!
In general, no... unless you know it's a function of a particular form (e.g. polynomial of some degree N) and there is enough information to constrain the function.
e.g. for a more "ordinary" counterexample (see Chuck's answer) for why you can't necessarily assume n^2 w/o knowing it's a quadratic equation, you could have f(n) = n4 - 6n3 + 12n2 - 6n, which has for n=0,1,2,3,4,5 f(n) = 0,1,4,9,40,145.
If you do know it's a particular form, there are some options... if the form is a linear addition of basis functions (e.g. f(x) = a + bcos(x) + csqrt(x)) then using least-squares can get you the unknown coefficients for the best fit using those basis functions.
See also this question.
You can apply statistical methods to try and guess the next answer, but that might not work very well if the function is like this one (c):
int evil(void){
static int e = 0;
if(50 == e++){
e = e * 100;
}
return e;
}
This function will return nice simple increasing numbers then ... BAM.
That's a hard problem.
You should check out the recurrence relation equation for special cases where it could be possible such a task.

Resources