Is there any algorithm that can find the sign of an arbitrary symbolic algebraic expression given in a "Tree - Form"?
I know that a general algorithm doesn't exist because the zero recognizion problem is undecidable for an arbitrary expression, but how should I approach the problem of finding the sign of an expression?
(how is this done in computer algebra?)
For example: sign(sqrt(2)-1) = ?
Evaluate the function value
You need function evaluator engine for that (it is not that hard to code) there is no way to evaluate sign only if you want to support +,- operations !!! All my function evaluators works like this:
compile the source text of the function
First create supported functions table (id,num of operands,name,pointer to function) like:
+,-,*,/,sin,cos,....
These will be the building blocks to any supported expression you need to evaluate. Do not forget to code all functions in your code too. Handle brackets (,) also as functions (push,pop). Group your functions by number of operands so +,- are with 1 and 2 operands (two different functions each !!!).
Now from expression extract:
variable names
constant names and values
number values
Into some kind of table/list:
variables[](id,name,value)
constants[](id,name,value)
numbers [](id, ,value)
And now finally construct compiled function string. My strings are set of two int's. First is type (which table to use) and second is id (index in table).
for example expression:
sign(sqrt(2)-1)
types:
id type
0 function
1 number
2 constant
3 variable
functions:
id name pointer
0 '(' ???
1 ')' ???
2 '+' ???
3 '-' ???
4 '*' ???
5 '/' ???
6 'sqrt' ???
7 'sign' ???
There are no variables or constants. The numbers are:
id value
0 2
1 1
compiled string:
type id
0 7 // sign(1 operand)
0 6 // sqrt(1 operand)
1 0 // 2
0 3 // - (2 operands)
1 1 // 1
After compilation you need to interpret the string and evaluate it's value.
init variables
op1=0`,`op2=0, // set all operands to zero (number depends on supported functions usually 2)
opn=0 // actual operands number
fx=none // actual function (for example none=-1)
fxn=0 // actual function operands number
read first record of compiled string
if it is value (number,constant,variable) set appropriate op? value with it and increment operand counter opn++.
if it is function set fx,fxn code with it
if opn == fxn
You reached needed operand count so execute function fx and init next function
op1=fxtab[fx].pointer(op1,op2,...)
fx=none,fxn=1
opn=1 (some spec functions can return more operands, then set op1,op2,.. opn=...)
if not end of string goto #2 but with next string record
at the end op1 should hold your output value
some example functions (C++ implementation):
double sign(double op1)
{
if (op1>0.0) return +1.0;
if (op1<0.0) return -1.0;
return 0.0;
}
double sqrt1(double op1) { return sqrt(op1); }
double plus1(double op1) { return op1; }
double minus1(double op1) { return -op1; }
double plus2(double op1,double op2) { return op1+op2; }
double minus2(double op1,double op2) { return op1-op2; }
[Notes]
You have to handle special cases like function = "";. Also beware spacing, case sensitivity because any error in compilation invalidates the result.
Speed is not a big issue this is interpreting-evaluation not numerical solution. All operations are called the same times as you would do on the paper.
You should also handle mathematic errors (overflows,invalid operands,NaN,Inf ...)
I usually group functions with the same number of operands to own type to simplify things
Related
In Python, what is the difference between expressions and statements?
Expressions only contain identifiers, literals and operators, where operators include arithmetic and boolean operators, the function call operator () the subscription operator [] and similar, and can be reduced to some kind of "value", which can be any Python object. Examples:
3 + 5
map(lambda x: x*x, range(10))
[a.x for a in some_iterable]
yield 7
Statements (see 1, 2), on the other hand, are everything that can make up a line (or several lines) of Python code. Note that expressions are statements as well. Examples:
# all the above expressions
print 42
if x: do_y()
return
a = 7
Expression -- from the New Oxford American Dictionary:
expression: Mathematics a collection
of symbols that jointly express a
quantity : the expression for the
circumference of a circle is 2πr.
In gross general terms: Expressions produce at least one value.
In Python, expressions are covered extensively in the Python Language Reference In general, expressions in Python are composed of a syntactically legal combination of Atoms, Primaries and Operators.
Python expressions from Wikipedia
Examples of expressions:
Literals and syntactically correct combinations with Operators and built-in functions or the call of a user-written functions:
>>> 23
23
>>> 23l
23L
>>> range(4)
[0, 1, 2, 3]
>>> 2L*bin(2)
'0b100b10'
>>> def func(a): # Statement, just part of the example...
... return a*a # Statement...
...
>>> func(3)*4
36
>>> func(5) is func(a=5)
True
Statement from Wikipedia:
In computer programming a statement
can be thought of as the smallest
standalone element of an imperative
programming language. A program is
formed by a sequence of one or more
statements. A statement will have
internal components (e.g.,
expressions).
Python statements from Wikipedia
In gross general terms: Statements Do Something and are often composed of expressions (or other statements)
The Python Language Reference covers Simple Statements and Compound Statements extensively.
The distinction of "Statements do something" and "expressions produce a value" distinction can become blurry however:
List Comprehensions are considered "Expressions" but they have looping constructs and therfore also Do Something.
The if is usually a statement, such as if x<0: x=0 but you can also have a conditional expression like x=0 if x<0 else 1 that are expressions. In other languages, like C, this form is called an operator like this x=x<0?0:1;
You can write you own Expressions by writing a function. def func(a): return a*a is an expression when used but made up of statements when defined.
An expression that returns None is a procedure in Python: def proc(): pass Syntactically, you can use proc() as an expression, but that is probably a bug...
Python is a bit more strict than say C is on the differences between an Expression and Statement. In C, any expression is a legal statement. You can have func(x=2); Is that an Expression or Statement? (Answer: Expression used as a Statement with a side-effect.) The assignment statement of x=2 inside of the function call of func(x=2) in Python sets the named argument a to 2 only in the call to func and is more limited than the C example.
Though this isn't related to Python:
An expression evaluates to a value.
A statement does something.
>>> x + 2 # an expression
>>> x = 1 # a statement
>>> y = x + 1 # a statement
>>> print y # a statement (in 2.x)
2
An expression is something that can be reduced to a value, for example "1+3" is an expression, but "foo = 1+3" is not.
It's easy to check:
print(foo = 1+3)
If it doesn't work, it's a statement, if it does, it's an expression.
Another statement could be:
class Foo(Bar): pass
as it cannot be reduced to a value.
Statements represent an action or command e.g print statements, assignment statements.
print 'hello', x = 1
Expression is a combination of variables, operations and values that yields a result value.
5 * 5 # yields 25
Lastly, expression statements
print 5*5
An expression is something, while a statement does something.
An expression is a statement as well, but it must have a return.
>>> 2 * 2 #expression
>>> print(2 * 2) #statement
PS:The interpreter always prints out the values of all expressions.
An expression is a statement that returns a value. So if it can appear on the right side of an assignment, or as a parameter to a method call, it is an expression.
Some code can be both an expression or a statement, depending on the context. The language may have a means to differentiate between the two when they are ambiguous.
STATEMENT:
A Statement is a action or a command that does something. Ex: If-Else,Loops..etc
val a: Int = 5
If(a>5) print("Hey!") else print("Hi!")
EXPRESSION:
A Expression is a combination of values, operators and literals which yields something.
val a: Int = 5 + 5 #yields 10
Expressions always evaluate to a value, statements don't.
e.g.
variable declaration and assignment are statements because they do not return a value
const list = [1,2,3];
Here we have two operands - a variable 'sum' on the left and an expression on the right.
The whole thing is a statement, but the bit on the right is an expression as that piece of code returns a value.
const sum = list.reduce((a, b)=> a+ b, 0);
Function calls, arithmetic and boolean operations are good examples of expressions.
Expressions are often part of a statement.
The distinction between the two is often required to indicate whether we require a pice of code to return a value.
References
Expressions and statements
2.3 Expressions and statements - thinkpython2 by Allen B. Downey
2.10. Statements and Expressions - How to Think like a Computer Scientist by Paul Resnick and Brad Miller
An expression is a combination of values, variables, and operators. A value all by itself is
considered an expression, and so is a variable, so the following are all legal expressions:
>>> 42
42
>>> n
17
>>> n + 25
42
When you type an expression at the prompt, the interpreter evaluates it, which means that
it finds the value of the expression. In this example, n has the value 17 and n + 25 has the
value 42.
A statement is a unit of code that has an effect, like creating a variable or displaying a
value.
>>> n = 17
>>> print(n)
The first line is an assignment statement that gives a value to n. The second line is a print
statement that displays the value of n.
When you type a statement, the interpreter executes it, which means that it does whatever
the statement says. In general, statements don’t have values.
An expression translates to a value.
A statement consumes a value* to produce a result**.
*That includes an empty value, like: print() or pop().
**This result can be any action that changes something; e.g. changes the memory ( x = 1) or changes something on the screen ( print("x") ).
A few notes:
Since a statement can return a result, it can be part of an expression.
An expression can be part of another expression.
Statements before could change the state of our Python program: create or update variables, define function, etc.
And expressions just return some value can't change the global state or local state in a function.
But now we got :=, it's an alien!
Expressions:
Expressions are formed by combining objects and operators.
An expression has a value, which has a type.
Syntax for a simple expression:<object><operator><object>
2.0 + 3 is an expression which evaluates to 5.0 and has a type float associated with it.
Statements
Statements are composed of expression(s). It can span multiple lines.
A statement contains a keyword.
An expression does not contain a keyword.
print "hello" is statement, because print is a keyword.
"hello" is an expression, but list compression is against this.
The following is an expression statement, and it is true without list comprehension:
(x*2 for x in range(10))
Python calls expressions "expression statements", so the question is perhaps not fully formed.
A statement consists of pretty much anything you can do in Python: calculating a value, assigning a value, deleting a variable, printing a value, returning from a function, raising an exception, etc. The full list is here: http://docs.python.org/reference/simple_stmts.html#
An expression statement is limited to calling functions (e.g.,
math.cos(theta)"), operators ( e.g., "2+3"), etc. to produce a value.
Say I have a recursive descent parser that defines a bunch of nested rules.
Expr ← Sum
Sum ← Product (('+' / '-') Product)*
Product ← Value (('*' / '/') Value)*
Value ← [0-9]+ / '(' Expr ')'
Say I am right ● here on the second Value in the process:
Expr ← Sum
Sum ← Product (('+' / '-') Product)*
Product ← Value (('*' / '/') ●)*
Value ← [0-9]+ / '(' Expr ')'
That would mean that I am somewhere in here in a nesting level let's say:
Expr
Sum
|Product
+
Product
|Product
-
Product
|Value
*
Value
|Value
*
●
When parsing with recursive descent, it is recursive so when Value returns, we get back to the "sequence" * parsing node, which then returns to the Product node, which returns to the product sequence node, etc. So it's easy to build up the parsing tree.
But let's say that you want to do this using an iterative stack. The question is, how to keep track of the nesting information so that you can say in your code (eventually):
function handleValue(state, string) {
// ...
}
function handleValueSequence(state, string) {
if (state.startedValueSequenceEarlier) {
wrapItUp(new ValueSequence(state.values))
}
}
function handleProduct(state, string) {
// ...
}
function handleProductSequence(state, string) {
if (state.startedProductSequenceEarlier) {
wrapItUp(new ProductSequence(state.products))
}
}
The tricky part is, this can be arbitrarily nested, so you might have:
Product
Value
Product
Value
Product
...
So if your function like handleProductSequence doesn't have any context other than the function's arguments, I can't tell how it should figure out how to "wrapItUp" and finally create that ProductSequence object. In that state object I added, I am trying to think of ways of adding a state.stack property or something, but I'm not sure what would go in there. Any help would be much appreciated.
Your stack has to contain "where you are" in the control flow. In a recursive descent parser, that will be effectively the same as where you are in the parse, so you could write a generalised LL parser in this fashion. Personally, I'd probably represent a production as an object with a list of tokens and a handler function. (Plus some extension for EBNF operators like *.) A state would then be a production, a position in the production, and a list of already matched values.
But it's hard to see a good reason to do that when LR parser generators already exist, using essentially this representation, and they can handle many more grammars.
Suppose I have the following code:
class proba {
boolean fun(Number n) {
return n == null || 0 == n;
}
}
This compiles without problem using openjdk 7 (debian wheezy), but fails to compile when using openjdk 8, with the following error (even when using -source 7):
proba.java:3: error: incomparable types: int and Number
return n == null || 0 == n;
^
1 error
How to go around this:
Is there a compiler option for this construct to continue working in java 8?
Should I make lots of consecutive ifs with instanceof checks of all of Number's subclasses and casting and then comparing one-by one? This seems ugly...
Other suggestions?
This is actually a bugfix (see JDK-8013357): the Java-7 behavior contradicted the JLS §15.21:
The equality operators may be used to compare two operands that are convertible (§5.1.8) to numeric type, or two operands of type boolean or Boolean, or two operands that are each of either reference type or the null type. All other cases result in a compile-time error.
In your case one operand is numeric type, while other is reference type (Number is not convertible to the numeric type), so it should be a compile-time error, according to the specification.
This change is mentioned in Compatibility Guide for Java 8 (search for "primitive").
Note that while your code compiles in Java-7 it works somewhat strangely:
System.out.println(new proba().fun(0)); // compiles, prints true
System.out.println(new proba().fun(0.0)); // compiles, prints false
System.out.println(new proba().fun(new Integer(0))); // compiles, prints false
That's why Java-7 promotes 0 to Integer object (via autoboxing), then compares two objects by reference which is unlikely what you want.
To fix your code, you may convert Number to some predefined primitive type like double:
boolean fun(Number n) {
return n == null || 0 == n.doubleValue();
}
If you want to compare Number and int - call Number.intValue() and then compare.
This question already has answers here:
Passing lists from one function to another in Swift
(2 answers)
Closed 7 years ago.
I am getting a Binary operator '/' cannot be applied to two (Int) operands error when I put the following code in a Swift playground in Xcode.
func sumOf(numbers: Int...) -> Int {
var sum = 0
for number in numbers {
sum += number
}
return sum
}
sumOf()
sumOf(42, 597, 12)
The above was a function calculating the total sum of any numbers.
Below is a function calculating the average of the numbers. The function is calling the sumOf() function from within itself.
func avg(numbers: Int...) -> Float {
var avg:Float = ( sumOf(numbers) ) / ( numbers.count ) //Binary operator '/' cannot be applied to two (Int) operands
return avg
}
avg(1, 2, 3);
Note: I have looked everywhere in stack exchange for the answer, but the questions all are different from mine because mine is involving two Ints, the same type and not different two different types.
I would like it if someone could help me to solve the problem which I have.
Despite the error message it seems that you cannot forward the sequence (...) operator. A single call of sumOf(numbers) within the agv() function gives an error cannot invoke sumOf with an argument of type ((Int))
The error is telling you what to do. If you refer to https://developer.apple.com/library/mac/documentation/AppleScript/Conceptual/AppleScriptLangGuide/reference/ASLR_operators.html
/ Division.
A binary arithmetic operator that divides the number to its left by the number to its right.
Class of operands: integer, real
Class of result: real
The second argument has to be real. Convert it like so. I don't use xcode, but I think my syntax is correct.
var avg:Float = ( sumOf(numbers) ) / Float( numbers.count )
I want to make a list with its elements representing the logic map given by
x_{n+1} = a*x_n(1-x_n)
I tried the following code (which adds stuff manually instead of a For loop):
x0 = Input["Enter x0"]
a = Input["a"]
M = {x0}
L[n_] := If[n < 1, x0, a*M[[n]]*(1 - M[[n]])]
Print[L[1]]
Append[M, L[1]]
Print[M]
Append[M, L[2]]
Print[M]
The output is as follows:
0.3
2
{0.3}
0.42
{0.3,0.42}
{0.3}
Part::partw: Part 2 of {0.3`} does not exist. >>
Part::partw: Part 2 of {0.3`} does not exist. >>
{0.3, 2 (1 - {0.3}[[2]]) {0.3}[[2]]}
{0.3}
It seems that, when the function definition is being called in Append[M,L[2]], L[2] is calling M[[2]] in the older definition of M, which clearly does not exist.
How can I make L use the newer, bigger version of M?
After doing this I could use a For loop to generate the entire list up to a certain index.
P.S. I apologise for the poor formatting but I could find out how to make Latex code work here.
Other minor question: What are the allowed names for functions and lists? Are underscores allowed in names?
It looks to me as if you are trying to compute the result of
FixedPointList[a*#*(1-#)&, x0]
Note:
Building lists element-by-element, whether you use a loop or some other construct, is almost always a bad idea in Mathematica. To use the system productively you need to learn some of the basic functional constructs, of which FixedPointList is one.
I'm not providing any explanation of the function I've used, nor of the interpretation of symbols such as # and &. This is all covered in the documentation which explains matters better than I can and with which you ought to become familiar.
Mathematica allows alphanumeric (only) names and they must start with a letter. Of course, Mathematic recognises many Unicode characters other than the 26 letters in the English alphabet as alphabetic. By convention (only) intrinsic names start with an upper-case letter and your own with a lower-case.
The underscore is most definitely not allowed in Mathematica names, it has a specific and widely-used interpretation as a short form of the Blank symbol.
Oh, LaTeX formatting doesn't work hereabouts, but Mathematica code is plenty readable enough.
It seems that, when the function definition is being called in
Append[M,L2], L2 is calling M[2] in the older definition of M,
which clearly does not exist.
How can I make L use the newer, bigger version of M?
M is never getting updated here. Append does not modify the parameters you pass to it; it returns the concatenated value of the arrays.
So, the following code:
A={1,2,3}
B=Append[A,5]
Will end up with B={1,2,3,5} and A={1,2,3}. A is not modfied.
To analyse your output,
0.3 // Output of x0 = Input["Enter x0"]. Note that the assignment operator returns the the assignment value.
2 // Output of a= Input["a"]
{0.3} // Output of M = {x0}
0.42 // Output of Print[L[1]]
{0.3,0.42} // Output of Append[M, L[1]]. This is the *return value*, not the new value of M
{0.3} // Output of Print[M]
Part::partw: Part 2 of {0.3`} does not exist. >> // M has only one element, so M[[2]] doesn't make sense
Part::partw: Part 2 of {0.3`} does not exist. >> // ditto
{0.3, 2 (1 - {0.3}[[2]]) {0.3}[[2]]} (* Output of Append[M, L[2]]. Again, *not* the new value of M *)
{0.3} // Output of Print[M]
The simple fix here is to use M=Append[M, L[1]].
To do it in a single for loop:
xn=x0;
For[i = 0, i < n, i++,
M = Append[M, xn];
xn = A*xn (1 - xn)
];
A faster method would be to use NestList[a*#*(1-#)&, x0,n] as a variation of the method mentioned by Mark above.
Here, the expression a*#*(1-#)& is basically an anonymous function (# is its parameter, the & is a shorthand for enclosing it in Function[]). The NestList method takes a function as one argument and recursively applies it starting with x0, for n iterations.
Other minor question: What are the allowed names for functions and lists? Are underscores allowed in names?
No underscores, they're used for pattern matching. Otherwise a variable can contain alphabets and special characters (like theta and all), but no characters that have a meaning in mathematica (parentheses/braces/brackets, the at symbol, the hash symbol, an ampersand, a period, arithmetic symbols, underscores, etc). They may contain a dollar sign but preferably not start with one (these are usually reserved for system variables and all, though you can define a variable starting with a dollar sign without breaking anything).