I have a complicated expression in maple which depends on four real parameters, say a,b,c,d. Let us call this expression f(a,b,c,d). This expression consists of derivatives, definite and indefinite integrals of hyperbolic functions. By indefinite integral I mean expressions like Int(g(x),x). The expression f is to big for maple to write out, and I would therefore like to evaluate it numerically for different values of a,b,c and d. I tried doing evalf(value(f(a1,b1,c1,d1)), but this never terminates in maple, which I guess means that maple first tries to simplify f algebraically and then plugs in the real values a1,b1,c1, and d1.
Could someone please help me with this?
After the symbolic manipulation Maple will return an expression in terms of other variables for example:
diff(x^2 + 2, x); will return "2 x"
now if you write evalf(%), it will not be able to evaluate to any numerical value because it does not know the value of x. Therefore you have to first use subs() function to substitute the value of x where you want to evaluate the resulting expression.
Thus, in your case it will be subs([x=2, y=5], f(a, b, c, d)) assuming that the evaluated expression has variables x and y.
Remove the value command. It tries to evaluate your integrals symbolically, which is probably impossible. Just use evalf.
Related
I'm supposed to write a predicate that does some math stuff. But I don't know how to pass numbers or return numbers.
Maybe you can give me an example?
Let's say a predicate divide/2 that takes two numbers a and b and returns a/b.
Yes, you pass numbers in in some arguments, and you get the result back in some other argument(s) (usually last). For example
divide( N, D, R) :-
R is N / D.
Trying:
112 ?- divide(100,5,X).
X = 20.
113 ?- divide(100,7,X).
X = 14.285714285714286.
Now, this predicate is divide/3, because it has three arguments: two for inputs and one for the output "information flow".
This is a simplified, restricted version of what a Prolog predicate can do. Which is, to not be that uni-directional.
I guess "return" is a vague term. Expression languages have expressions e-value-ated so a function's last expression's value becomes that function's "return" value; Prolog does not do that. But command-oriented languages return values by putting them into some special register. That's not much different conceptually from Prolog putting some value into some logvar.
Of course unification is more complex, and more versatile. But still, functions are relations too. Predicates "return" values by successfully unifying their arguments with them, or fail to do so, as shown in the other answer.
Prolog is all about unifying variables. Predicates don't return values, they just succeed or fail.
Typically when a predicate is expected to produce values based on some of the arguments then the left-most arguments are inputs and the right-most are the outputs. However, many predicates work with allowing any argument to be an input and any to be a output.
Here's an example for multiply showing how it is used to perform divide.
multiply(X,Y,Z) :- number(X),number(Y),Z is X * Y.
multiply(X,Y,Z) :- number(X),number(Z),X \= 0,Y is Z / X.
multiply(X,Y,Z) :- number(Y),number(Z),Y \= 0,X is Z / Y.
Now I can query it like this:
?- multiply(5,9,X).
X = 45 .
But I can easily do divide:
?- multiply(5,X,9).
X = 1.8 .
It even fails if I try to do a division by 0:
?- multiply(X,0,9).
false.
Here's another approach. So let's say you have a list [22,24,34,66] and you want to divide each answer by the number 2. First we have the base predicate where if the list is empty and the number is zero so cut. Cut means to come out of the program or just stop don't go to the further predicates. The next predicate checks each Head of the list and divides it by the number A, meaning (2). And then we simply print the Answer. In order for it to go through each element of the list we send back the Tail [24,34,66] to redo the steps. So for the next step 24 becomes the Head and the remaining digits [34,66] become the Tail.
divideList([],0,0):-!.
divideList([H|T],A,Answer):-
Answer is H//A,
writeln(Answer),
divideList(T,A,_).
?- divideList([22,24,34,66],2,L).
OUTPUT:
11
12
17
33
Another simpler approach:
divideList([],_,[]).
divideList([H|T],A,[H1|L]):-
H1 is H//A,!,
divideList(T,A,L).
?-divideList([22,4,56,38],2,Answer).
Answer = [11, 2, 28, 19]
I can create a recursive formula from recurrences where it only passes down one argument (something like $T(n/2)$). However, for a case like this where the value of $u$ and $v$ are different, how do I put them together? This is the problem:
The call to recursive function RecursiveFunction(n, n) for some n > 2
RecursiveFunction(a, b)
if a >= 2 and b >= 2
u=a/2
v=b-1
RecursiveFunction(u, v)
The end goal is to find the tight asymptotic bounds for the worst-case running time, but I just need a formula to start first.
There are in fact two different answers to this, depending on the relative sizes of a and b.
The function can be written as follows:
Where C is some constant work done per call (if statement, pushing u, v onto the call stack etc.). Since the two variables evolve independently, we can analyse their evolution separately.
a - consider the following function:
Expanding the iterative case by m times:
The stopping condition a < 2 is such that:
b - as before:
The complexity of T(a, b) thus depends on which variable reaches its stopping condition first, i.e. the smallest between m and n:
Let's say I have a DFA with alphabet {0,1} which basically accepts any strings as long as there is no consecutive 0's (at most one 0 at a time). How do I express this in a mathematical notation?
I was thinking of any number of 1's followed by either one or none 0's, then any number of 1's..... but couldn't figure out the appropriate mathematical notation for it.
My attempt but obviously incorrect since 1010 should be accepted but the notation does not indicate so:
As a regular expression you could write this as 1*(01+)*0?. Arbitrary many ones, then arbitrary many groups of exactly one zero followed by at least one one, and in the end possibly one zero. Nico already wrote as much in a comment. Personally I'd consider such a regular expression sufficiently formal to call it mathematical.
Now if you want to write this using exponents, you could do something like
L = {1a (0 11+bi)c 0d mod 2 | a,bi,c,d ∈ ℕ for 1≤i≤c}
Writing a bit of formula in the exponents has the great benefit that you don't have to split the place where you use the exponent and the place where you define the range. Here all my numbers are natural numbers (including zero). Adding one means at least one repetition. And the modulo 2 makes the exponent 0 or 1 to express the ? in the regular expression.
Of course, there is an implied assumption here, namely that the c serves as a kind of loop, but it doesn't repeat the same expression every time, but the bi changes for each iteration. The range of the i implies this interpretation, but it might be considered confusing or even incorrect nonetheless.
The proper solution here would be using some formal product notation using a big ∏ with a subscript i = 1 and a superscript c. That would indicate that for every i from 1 through c you want to compute the given expression (i.e. 011+bi) and concatenate all the resulting words.
You could also give a recursive definition: The minimal fixpoint of the following definition
L' = {1, 10} ∪ {1a 0 b | a ∈ ℕ, a > 0, b ∈ L'}
is the language of all words which begin with a 1 and satisfy your conditions. From this you can build
L = {ε, 0} ∪ L' ∪ {0 a | a ∈ L'}
so you add the empty word and the lone zero, then take all the words from L' in their unmodified form and in the form with a zero added in front.
Integers can be used to store individual numbers, but not mathematical expressions. For example, lets say I have the expression:
6x^2 + 5x + 3
How would I store the polynomial? I could create my own object, but I don't see how I could represent the polynomial through member data. I do not want to create a function to evaluate a passed in argument because I do not only need to evaluate it, but also need to manipulate the expression.
Is a vector my only option or is there a more apt solution?
A simple yet inefficient way would be to store it as a list of coefficients. For example, the polynomial in the question would look like this:
[6, 5, 3]
If a term is missing, place a zero in its place. For instance, the polynomial 2x^3 - 4x + 7 would be represented like this:
[2, 0, -4, 7]
The degree of the polynomial is given by the length of the list minus one. This representation has one serious disadvantage: for sparse polynomials, the list will contain a lot of zeros.
A more reasonable representation of the term list of a sparse polynomial is as a list of the nonzero terms, where each term is a list containing the order of the term and the coefficient for that order; the degree of the polynomial is given by the order of the first term. For example, the polynomial x^100+2x^2+1 would be represented by this list:
[[100, 1], [2, 2], [0, 1]]
As an example of how useful this representation is, the book SICP builds a simple but very effective symbolic algebra system using the second representation for polynomials described above.
A list is not the only option.
You can use a map (dictionary) mapping the exponent to the corresponding coefficient.
Using a map, your example would be
{2: 6, 1: 5, 0: 3}
A list of (coefficient, exponent) pairs is quite standard. If you know your polynomial is dense, that is, all the exponent positions are small integers in the range 0 to some small maximum exponent, you can use the array, as I see Óscar Lopez just posted. :)
You can represent expressions as Expression Trees. See for example .NET Expression Trees.
This allows for much more complex expressions than simple polynomials and those expressions can also use multiple variables.
In .NET you can manipulate the expression tree as a tree AND you can evaluate it as a function.
Expression<Func<double,double>> polynomial = x => (x * x + 2 * x - 1);
double result = polynomial.Compile()(23.0);
An object-oriented approach would say that a Polynomial is a collection of Monomials, and a Monomial encapsulates a coefficient and exponent together.
This approach works when when you have a polynomial like this:
y(x) = x^1000 + 1
An approach that tied a data structure to a polynomial order would be terribly wasteful for this pathological case.
You need to store two things:
The degree of your polynomial (e.g. "3")
A list containing each coefficient (e.g. "{3, 0, 2}")
In standard C++, "std::vector<>" and "std::list<>" can do both.
Vector/array is obvious choice. Depending on type of expressions you may consider some sort of sparse vector type (custom made, i.e. based on dictionary or even linked list if you expressions have 2-3 non-zero coefficients 5x^100+x ).
In either case exposing through custom class/interface would be beneficial as you can replace implementation later. You would likely want to provide standard operations (+, -, *, equals) if you plan to write a lot of expression manipulation code.
Just store the coefficients in an array or vector. For example, in C++ if you are only using integer coefficients, you could use std::vector<int>, or for real numbers, std::vector<double>. Then you just push the coefficients in order and access them by variable exponent number.
For example (again in C++), to store 5*x^3 + 9*x - 2 you might do:
std::vector<int> poly;
poly.push_back(-2); // x^0, acceesed with poly[0]
poly.push_back(9); // x^1, accessed with poly[1]
poly.push_back(0); // x^2, etc
poly.push_back(5); // x^3, etc
If you have large, sparse, polynomials, then maybe you'd want to use a map instead of a vector. If you have fixed sized lengths, then you'd perhaps use an fixed length array instead of a vector.
I've used C++ for examples, but this same scheme can be used in any language.
You can also transform it into reverse Polish notation:
6x^2 + 5x + 3 -> x 2 ^ 6 * x 5 * + 3 +
Where x and numbers are "pushed" onto a stack and operations (^,*,+) take the two top-most values from the stack and replace them with the result of the operation. In the end you get the resultant value on the stack.
In this form it's easy to calculate arbitrarily complex expressions.
This representation is also close to tree representation of expressions where non-leaf tree nodes represent operations and functions and leaf nodes are for constants and variables.
What's good about trees is that you can also easily evaluate expressions and you can also do things like symbolic differentiation on them. Both have recursive nature.
There are some special operators in Prolog, one of them is is, however, recently I came across the =:= operator and have no idea how it works.
Can someone explain what this operator does, and also where can I find a predefined list of such special operators and what they do?
I think the above answer deserves a few words of explanation here nevertheless.
A short note in advance: Arithmetic expressions in Prolog are just terms ("Everything is a term in Prolog"), which are not evaluated automatically. (If you have a Lisp background, think of quoted lists). So 3 + 4 is just the same as +(3,4), which does nothing on its own. It is the responsibility of individual predicates to evaluate those terms.
Several built-in predicates do implicit evaluation, among them the arithmetic comparsion operators like =:= and is. While =:= evaluates both arguments and compares the result, is accepts and evaluates only its right argument as an arithmetic expression.
The left argument has to be an atom, either a numeric constant (which is then compared to the result of the evaluation of the right operand), or a variable. If it is a bound variable, its value has to be numeric and is compared to the right operand as in the former case. If it is an unbound variable, the result of the evaluation of the right operand is bound to that variable. is is often used in this latter case, to bind variables.
To pick up on an example from the above linked Prolog Dictionary: To test if a number N is even, you could use both operators:
0 is N mod 2 % true if N is even
0 =:= N mod 2 % dito
But if you want to capture the result of the operation you can only use the first variant. If X is unbound, then:
X is N mod 2 % X will be 0 if N is even
X =:= N mod 2 % !will bomb with argument/instantiation error!
Rule of thumb: If you just need arithmetic comparison, use =:=. If you want to capture the result of an evaluation, use is.
?- 2+3 =:= 6-1.
true.
?- 2+3 is 6-1.
false.
Also please see docs http://www.swi-prolog.org/pldoc/man?predicate=is/2
Complementing the existing answers, I would like to state a few additional points:
An operator is an operator
First of all, the operator =:= is, as the name indicates, an operator. In Prolog, we can use the predicate current_op/3 to learn more about operators. For example:
?- current_op(Prec, Type, =:=).
Prec = 700,
Type = xfx.
This means that the operator =:= has precedence 700 and is of type xfx. This means that it is a binary infix operator.
This means that you can, if you want, write a term like =:=(X, Y) equivalently as X =:= Y. In both cases, the functor of the term is =:=, and the arity of the term is 2. You can use write_canonical/1 to verify this:
?- write_canonical(a =:= b).
=:=(a,b)
A predicate is not an operator
So far, so good! This has all been a purely syntactical feature. However, what you are actually asking about is the predicate (=:=)/2, whose name is =:= and which takes 2 arguments.
As others have already explained, the predicate (=:=)/2 denotes arithmetic equality of two arithmetic expressions. It is true iff its arguments evaluate to the same number.
For example, let us try the most general query, by which we ask for any solution whatsoever, using variables as arguments:
?- X =:= Y.
ERROR: Arguments are not sufficiently instantiated
Hence, this predicate is not a true relation, since we cannot use it for generating results! This is a quite severe drawback of this predicate, clashing with what you commonly call "declarative programming".
The predicate only works in the very specific situation that both arguments are fully instantiated. For example:
?- 1 + 2 =:= 3.
true.
We call such predicates moded because they can only be used in particular modes of usage. For the vast majority of beginners, moded predicates are a nightmare to use, because they require you to think about your programs procedurally, which is quite hard at first and remains hard also later. Also, moded predicates severely limit the generality of your programs, because you cannot use them on all directions in which you could use pure predicates.
Constraints are a more general alternative
Prolog also provides much more general arithmetic predicates in the form of arithmetic constraints.
For example, in the case of integers, try your Prolog system's CLP(FD) constraints. One of the most important CLP(FD) constraints denotes arithmetic equality and is called (#=)/2. In complete analogy to (=:=)/2, the operator (#=)/2 is also defined as an infix operator, and so you can write for example:
| ?- 1 + 2 #= 3.
yes
I am using GNU Prolog as one particular example, and many other Prolog systems also provide CLP(FD) implementations.
A major attraction of constraints is found in their generality. For example, in contrast to (=:=)/2, we get with the predicate (#=)/2:
| ?- X + 2 #= 3.
X = 1
| ?- 1 + Y #= 3.
Y = 2
And we can even ask the most general query:
| ?- X #= Y.
X = _#0(0..268435455)
Y = _#0(0..268435455)
Note how naturally these predicates blend into Prolog and act as relations between integer expressions that can be queried in all directions.
Depending on the domain of interest, my recommendition is to use CLP(FD), CLP(Q), CLP(B) etc. instead of using more low-level arithmetic predicates.
Also see clpfd, clpq and clpb for more information.
Coincidentally, the operator =:= is used by CLP(B) with a completely different meaning:
?- sat(A =:= B+1).
A = 1,
sat(B=:=B).
This shows that you must distinguish between operators and predicates. In the above case, the predicate sat/1 has interpreted the given expression as a propositional formula, and in this context, =:= denotes equality of Boolean expressions.
I found my own answer, http://www.cse.unsw.edu.au/~billw/prologdict.html
Its an ISO core standard predicate operator, which cannot be bootstrapped from unification (=)/2 or syntactic equality (==)/2. It is defined in section 8.7 Arithmetic Comparison. And it basically behaves as follows:
E =:= F :-
X is E,
Y is F,
arithmetic_compare(=, X, Y).
So both the left hand side (LHS) and right hand side (RHS) must be arithmetic expressions that are evaluted before they are compared. Arithmetic comparison can compare across numeric types. So we have:
GNU Prolog 1.4.5 (64 bits)
?- 0 = 0.0.
no
?- 0 == 0.0
no
?- 0 =:= 0.0.
yes
From Erlang I think it could be good to annotate that as syntax are mostly look alike to Prolog.
=:= expression is meaning of exactly equal.
such as in JavaScript you can use === to also see if the type of the variables are same.
Basically it's same logic but =:= is used in functional languages as Prolog, Erlang.
Not much information but hope it could help in some way.
=:= is a comparison operator.A1 =:= A2 succeeds if values of expressions A1 and A2 are equal.
A1 == A2 succeeds if terms A1 and A2 are identical;