I'm trying to build a program in Pascal to differentiate mathematical functions. It's working very well (calculate min/max, symmetry, drawing the graph, etc.) but I have to put the functions (i.e. x^3+3x+2) into the source code like this:
function f(x : real): real;
begin
f := x * x * x + 3 * x + 2;
end;
Though, I want the user to define the function to differentiate. Obviosly the readln function does not help.
Somebody told me the only solution would be a specific parser. But it's very difficult, and I don't know how to do it.
My idea would be to extract the function into a *.txt file for example so that it could be changed easily. Is that possible?
Can somebody show me a parser which could solve this problem or have anybody some other great solution?
I would really appreciate your help!
Thanks in advance ;)
Free Pascal ships with the symbolic package, which has both a parser and evaluator for mathematical expressions. You can probably use this as a starting point. See the documentation for usage.
There are also a number of parsers/evalutaors on SWAG:
EQUATE.PAS (short, clean evaluator)
PARSMATH.PAS (very short example code)
Math Parsing Unit (undocumented, kind of messy)
Math Evaluations (Somewhat cryptic.)
Nice Expression Parser (Small, seems well done.)
Expression Evaluator (Messier, includes trig functions.)
Math Expression Evaluator (not well documented)
Equation Parser (converts equations to arrays of coefficients)
Text Formula Parser (fairly complete parser/evaluator unit)
I bolded the ones I thought were the most useful. I don't think any of them are as complete as the symbolic package in my other answer, but they might be worth reading if you need help.
(All of this is fairly old code. Unless otherwise stated, the rule with SWAG is to treat this stuff as having a new-style BSD license)
Related
I had the following code, which defines a simple function taking two real variables as arguments and returning a complex number. The function call would not return in a minute's time. I determined the cause was inappropriate us of sympify (see below)
%%time
from sympy import *
x,t=symbols('x t')
e_psi_sw=sin(2*pi*x) + exp(1j*t)*sin(pi*x)
pdf=conjugate(e_psi_sw)*e_psi_sw
integrate(pdf*x,(x,0,1))
It's faster if you use sympy's I instead of the complex Python float 1j. It is generally best to avoid using floats unnecessarily in sympy.
Also declaring the symbols x and t to be real results in a simpler integrand that can be integrated more easily.
I was calling sympify with a string rather than a bare expression. When I removed the quotation marks, the integral ran quickly and the other issues I cited here were also resolved.
I did change j to I also...
I am defining a function that takes as input a function and I want to specify it in the input type i.e. Operat[_?FunctionQ]:=...
But there is no functionQ as of yet in mathematica. How do I get aroud this except not specifying any type at all.
Any ideas?
Oh!
This: Test if an expression is a Function?
may be the answer i am looking for. I am reading further
Is the solution proposed there robust?, i.e.:
FunctionQ[_Function | _InterpolatingFunction | _CompiledFunction] = True;
FunctionQ[f_Symbol] := Or[
DownValues[f] =!= {},
MemberQ[ Attributes[f], NumericFunction ]]
FunctionQ[_] = False;
The exhibited definition has great utility. The question is: what exactly constitutes a function in Mathematica? Pure functions and the like are easily to classify as functions, but what about definitions that involve pattern-matching? Consider:
h[g[x_]] ^:= x + 1
Is h to be considered a function? If so, it will be hard to identify as it will entail examining the up-values of every symbol in the system to make that determination. Is g a function? It has an up-value, but g[x] is an inert expression.
What about head composition:
f[x_][y_][z_] := x + y + z
Is f a function? How about f[1] or f[1][2]?
And then there are the various capabilities like JLink and NETLink:
Needs["JLink`"]
obj = JavaNew["java.util.Date"]
obj#toString[]
Is obj#toString a function?
I hate to bring up these problems without offering solutions -- but I want to emphasize that the question as to what constitutes a function in the Mathematica context is a tricky one. It is tricky from both the theoretical and practical standpoints.
I think that the answer to whether the exhibited function test is complete really depends upon the types of expressions that you will be feeding it in your specific application.
I wanted to ask how can I can write this in MATLAB.
I want to integrate fp(z) with z(0,x). I tried this :
fpz=#(z) f1x(z) ./ quadl(f1x(z),0,1);
sol=int(fpz,0,x) --> i also tried sol=quadl(fpz,0,x)
y=solve('y=sol',x)
xf=# (y) y ; -->this is the function i want
where f1x=# (x) 1 ./(x.^2+1) and fpx = #(x) f1x(x) ./ quadl(f1x,0,1);
but it doesn't work.
Hello,thanks for helping.
The problem is that i want an analytically solution and i can't get one.
I want f1x to give me " 1/x^2+1" , fpx "4/pi*(1+x^2) and fpz "4ArcTan(x)/pi", instead of giving me "f1x=# 1./(x^2+1)"..
With the code you send me ,still the same problem.
I managed to come into this :
f1x=# (x) 1 ./(x.^2+1)
fpx = #(x) f1x(x) ./ quadl(f1x,0,1)
f2z=# (z) 1 ./(z.^2+1);
fpz=#(z) fpx(z) ./ quadl(f2z,0,1)
sol=int(fpz(z),z,0,x)
y=solve(subs('y=sol'),x)
xf=# (y) y
The "sol" and "y=" gives me analytically answer but it is wrong because i assume f1x and fpx,fpz doesn't return into analytically expressions.
0 Your definition of fpz doesn't make any sense; as Marcin already said, you're trying to integrate something that isn't a function. This shouldn't be a problem for your alternative version with f2z. I think the code in the original question should have had just f1x rather than f1x(z) in the first line.
1 Your revised version with f2z has a different problem: now in fpz you aren't actually providing the function with an argument.
The following code seems to be the kind of thing you had in mind, and works fine for me (in MATLAB R2008a, as it happens, but none of this should be different in other versions):
f1x = #(x) 1 ./ (x.^2+1);
fpx = #(x) f1x(x) ./ quadl(f1x,0,1);
fpz = #(z) fpx(z) ./ quadl(fpx,0,1);
Now evaluating fpz(3), for instance, spins for about half a second (on my old slow laptop computer) and returns 0.1273.
So I think the problems you've been having with integration of anonymous functions are just a matter of not being quite careful enough to distinguish between the function itself and a particular value of the function.
You have some further questions about the "solve" and "int" functions in the Symbolic Math Toolbox. You should take the following with a pinch of salt because I don't have that toolbox and am relying on the online documentation for it.
3 You're feeding the names of functions you've defined in MATLAB to the Symbolic Math Toolbox functions. I don't think that is supposed to work; "int" and "solve" expect explicit algebraic expressions, not MATLAB functions. (And, further, your functions all use numerical integration -- quad, quadl, etc. -- and there's no possible way that the symbolic functions can do anything useful with that.)
Finally: When you're asking questions of this sort, it's helpful if rather than "it doesn't work" you say how it doesn't work. For instance, your most recent comment is much more useful ("it gives me ..." followed by the actual output you get from MATLAB).
I have an internal wiki and I created a function w(argument), which directly opens the corresponding page on my wiki using browseURL(url, browser). However, instead of w(argument), I'd like to replace it by #argument, similar to ?argument. Does somebody know if such a function definition with a shortkey is possible within R
Thanks a lot for your help
BR
Martin
No. What you are looking for is to define a new unary operator in R, and that isn't possible. (And # is the comment character in R so is used already anyway, so that wouldn't work.)
This post by Brian Ripley, in response to a similarly motivated question, has a bit more explanation (not much)
'#' starts a comment in R, so that will never get passed the parser. You'll have to modify the core and recompile R if you really want #foo to do something other than nothing.
You can change what ?foo does by reassigning it:
> assign("?",function(x){cat("HALP!\n")})
> ?foo
HALP!
Obviously you'd make it fall through to the default help system if the arg isn't what you are interested in, but this is pretty ugly.
You could define a binary operator, then pass anything in to the first argument, e.g.,
"%w%" <- function(x, y) w(y)
1%w%argument
It's 4 keys rather than 1, but that's about as close as you can get without major reworking of R.
Like Smalltalk or Lisp?
EDIT
Where control structures are like:
Java Python
if( condition ) { if cond:
doSomething doSomething
}
Or
Java Python
while( true ) { while True:
print("Hello"); print "Hello"
}
And operators
Java, Python
1 + 2 // + operator
2 * 5 // * op
In Smalltalk ( if I'm correct ) that would be:
condition ifTrue:[
doSomething
]
True whileTrue:[
"Hello" print
]
1 + 2 // + is a method of 1 and the parameter is 2 like 1.add(2)
2 * 5 // same thing
how come you've never heard of lisp before?
You mean without special syntax for achieving the same?
Lots of languages have control structures and operators that are "really" some form of message passing or functional call system that can be redefined. Most "pure" object languages and pure functional languages fit the bill. But they are all still going to have your "+" and some form of code block--including SmallTalk!--so your question is a little misleading.
Assembly
Befunge
Prolog*
*I cannot be held accountable for any frustration and/or headaches caused by trying to get your head around this technology, nor am I liable for any damages caused by you due to aforementioned conditions including, but not limited to, broken keyboard, punched-in screen and/or head-shaped dents in your desk.
Pure lambda calculus? Here's the grammar for the entire language:
e ::= x | e1 e2 | \x . e
All you have are variables, function application, and function creation. It's equivalent in power to a Turing machine. There are well-known codings (typically "Church encodings") for such constructs as
If-then-else
while-do
recursion
and such datatypes as
Booleans
integers
records
lists, trees, and other recursive types
Coding in lambda calculus can be a lot of fun—our students will do it in the undergraduate languages course next spring.
Forth may qualify, depending on exactly what you mean by "no control structures or operators". Forth may appear to have them, but really they are all just symbols, and the "control structures" and "operators" can be defined (or redefined) by the programmer.
What about Logo or more specifically, Turtle Graphics? I'm sure we all remember that, PEN UP, PEN DOWN, FORWARD 10, etc.
The SMITH programming language:
http://esolangs.org/wiki/SMITH
http://catseye.tc/projects/smith/
It has no jumps and is Turing complete. I've also made a Haskell interpreter for this bad boy a few years back.
I'll be first to mention brain**** then.
In Tcl, there's no control structures; there's just commands and they can all be redefined. Every last one. There's also no operators. Well, except for in expressions, but that's really just an imported foreign syntax that isn't part of the language itself. (We can also import full C or Fortran or just about anything else.)
How about FRACTRAN?
FRACTRAN is a Turing-complete esoteric programming language invented by the mathematician John Conway. A FRACTRAN program is an ordered list of positive fractions together with an initial positive integer input n. The program is run by updating the integer (n) as follows:
for the first fraction f in the list for which nf is an integer, replace n by nf
repeat this rule until no fraction in the list produces an integer when multiplied by n, then halt.
Of course there is an implicit control structure in rule 2.
D (used in DTrace)?
APT - (Automatic Programmed Tool) used extensively for programming NC machine tools.
The language also has no IO capabilities.
XSLT (or XSL, some say) has control structures like if and for, but you should generally avoid them and deal with everything by writing rules with the correct level of specificity. So the control structures are there, but are implied by the default thing the translation engine does: apply potentially-recursive rules.
For and if (and some others) do exist, but in many many situations you can and should work around them.
How about Whenever?
Programs consist of "to-do list" - a series of statements which are executed in random order. Each statement can contain a prerequisite, which if not fulfilled causes the statement to be deferred until some (random) later time.
I'm not entirely clear on the concept, but I think PostScript meets the criteria, although it calls all of its functions operators (the way LISP calls all of its operators functions).
Makefile syntax doesn't seem to have any operators or control structures. I'd say it's a programming language but it isn't Turing Complete (without extensions to the POSIX standard anyway)
So... you're looking for a super-simple language? How about Batch programming? If you have any version of Windows, then you have access to a Batch compiler. It's also more useful than you'd think, since you can carry out basic file functions (copy, rename, make directory, delete file, etc.)
http://www.csulb.edu/~murdock/dosindex.html
Example
Open notepad and make a .Bat file on your Windows box.
Open the .Bat file with notepad
In the first line, type "echo off"
In the second line, type "echo hello world"
In the third line, type "pause"
Save and run the file.
If you're looking for a way to learn some very basic programming, this is a good way to start. (Just be careful with the Delete and Format commands. Don't experiment with those.)