When asking for a symbol .free_symbols I get something in curly braces (which is a set).
If I use this set as list of arguments for lambdify of sympy it seems it is converted into a list. This is hinted in the doc but I suggest a warning to be given here when this conversion is made. A good reason for this is that the ordering of the symbols may be altered in this conversion.
In my case
_chiSquare.free_symbols gives {c_95_0, c_95_1}
but
list({'c_95_0', 'c_95_1'}) gives ['c_95_1', 'c_95_0']
I like to automate the making of numerical functions using .free_symbols but this is hard to work with if order of variable is changed without notice.
My question is how one is supposed to deal with free_symbols and lambdify in a way that arguments order is kept fixed.
I think it is better to keep track of the symbols explicitly rather than using free_symbols.
If you must work from free_symbols then you can sort them to get a consistent ordering:
In [3]: sorted((x*y).free_symbols, key=lambda s: s.name)
Out[3]: [x, y]
In a dynamic system my base values are all functions of time, d(t). I create the variable d using d = Function('d')(t) where t = S('t')
Obviously it's very common to have derivatives of d (rates of change like velocity etc.). However the default printing of diff(d(t)) gives:-
Derivative(d(t), t)
and using pretty printing in ipython (for e.g.) gives a better looking version of:-
d/dt (d(t))
The functions which include the derivatives of d(t) are fairly long in my problems however, and I'd like the printed representation to be something like d'(t) or \dot(d)(t) (Latex).
Is this possible in sympy? I can probably workaround this using subs but would prefer a generic sympy_print function or something I could tweak.
I do this by substitution. It is horribly stupid, but it works like a charm:
q = Function('q')(t)
q_d = Function('\\dot{q}')(t)
and then substitute with
alias = {q.diff(t):q_d, } # and higher derivatives etc..
hd = q.diff(t).subs(alias)
And the output hd has a pretty dot over it's head!
As I said: this is a work-around and works, but you have to be careful in order to substitute correctly (Also for q_d.diff(t), which must be q_d2 and so on! You can have one big list with all replacements for printing and just apply it after the relevant mathematical steps.)
The vector printing module that you already found is the only place where such printing is implemented in SymPy.
from sympy.physics.vector import dynamicsymbols
from sympy.physics.vector.printing import vpprint, vlatex
d = dynamicsymbols('d')
vpprint(d.diff()) # ḋ
vlatex(d.diff()) # '\\dot{d}'
The regular printers (pretty, LaTeX, etc) do not support either prime or dot notation for derivatives. Their _print_Derivative methods are written so that they also work for multivariable expressions, where one has to specify a variable by using some sort of d/dx notation.
It would be nice to have an option for shorter derivative notation in general.
I am trying to estimate numerical estimate of a large symbolic expression that is composed of a varying number of arguments (for e.g. 21 here, but assume an unknown number of variables for other expressions). So, I use sym.lambdify() to convert the symbolic expression (expression_sym) to a python function (fn_expression) that I can use to find a numerical estimate for its corresponding symbolic expression (expression_sym).
import sympy as sym
symbols_tuple = tuple(expression_sym.free_symbols)
fn_expression = sym.lambdify(symbols_tuple, expression_sym)
Now I source constant numerical values for all symbols present in symbols_tuple in a variable called free_symbols_val. However, free_symbols_val also contains some other variable names that are not present in symbols_tuple.
free_symbols_val = foo() # numerical values for all symbols from some function foo()
Now that I have all the numerical values for all the symbols/variables present in fn_expression, I can simply pass the variable names that are known to be part of expression_sym. I cannot directly use free_symbols_val as input because it contains more variables than present in fn_expression.
fn_num = fn_expression(symbols_tuple)
However, using symbols_tuple directly as an argument for fn_expression() gives a TypeError as follow:
TypeError: <lambda>() takes exactly 21 arguments (1 given)
Note:
I know about *args in python that can be used to assign an unknown number of arguments, but that is not working here, i.e. if I use fn_expression(*symbols_tuple) it doesn't work and throws the following error:
TypeError: can't convert expression to float
I am trying to solve an exercise in SML like ;
Write an ML program to be used for a multiple choice exam containing 10 questions. Your program should include the following:
o The answer key of the exam
e.g.
val key= “adabcbaadb”;
o Type definition for a record (info) which contains name and answers of a student.
e.g. {name=”Ali”,ans=”abadccdadb”}
o Type definition for a tuple (result) which contains name and score of a student.
e.g. ("Ali",60)
o Write as many functions as needed to take a list of records of type info containing the information of 3 students, calculate their scores, and convert them into a list of tuples of type result. You can write other supporting functions as well
e.g.
- val stuInfo:info list=[{name=”Ali”,ans=”abadccdadb”},
{name=”Ege”,ans=”cbbdacabda”},
{name=”Can”,ans=”adabcbaadb”}];
- val results = calculate(stuInfo);
val results = [("Ali",60),("Ege",20),("Can",100)] : result list
o Write as many functions as needed to calculate the average score, and return the students who received a score above the average.
e.g.
-val aboveList=aboveAvg(results);
val aboveList = [("Ali",60),("Can",100)] : result list
Notes:
Make sure you give the types of your parameters and return value in all your functions.
Paranthesize your expressions.
Use explode function which converts a string to a character array
e.g.
- explode "abc";
val it = [#"a",#"b",#"c"] : char list
My written code for this exercise is below ; but my code is not working :/ Where is my mistake ?
val answer_key="ddacbadbca";
type student_information={s_name:string,s_choice:string};
type student_result=string*int;
val student:info list=[{s_name="David",s_choice="adcbbaccad"},{s_name="John",s_choice="ccdabdbbcc"},{s_name="Alice",s_choice="abdaccacdb"}];
val 3studentsResult:student_result=average(student_information);
fun average ((h::t):student_information list):student_result list=student_score(explode"#ans h",explode"key")::average(t);
val sum=0;
fun student_score(((a::b,c::d):'a list):'a list) = (if(a=c) then sum=sum+10 else sum=sum+0 )::student_score(b,d);
Thanks
There are multiple issues about this code. Before starting, I should recommend you to work on your styling, you can use some spaces and extra lines between functions to see what you are doing easily, like this:
val answer_key = "ddacbadbca";
type student_information = {s_name:string, s_choice:string};
type student_result = string * int;
val student : student_information list =
[{s_name="David", s_choice="adcbbaccad"},
{s_name="John", s_choice="ccdabdbbcc"},
{s_name="Alice", s_choice="abdaccacdb"}];
You might also want to keep your variable and type names consistent. I think the convention is to use snake case (like snake_case) for type names and camel case (like camelCase) for variable and function names.
Here are some of your actual mistakes:
For your student variable, you give the type info list, which doesn't exist in your program. I assume your student_information variable used to be named info, so you should change one of those to the other.
You have a variable named 3studentsResult. Variables cannot start with numbers, they have to start with letters. You have to rename that variable, to something like threeStudentsResult.
In your 3studentsResult variable, you are using the average function that you define later. That doesn't work in Standard ML. You should define a function before using it. (Unless you need mutual recursion, you can use the and keyword then, but it's irrelevant to your problem.) Therefore, define average before 3studentsResult, and define student_score before average.
Even after fixing these, your student_score function is incorrect. I assume sum=sum+10 means that you are trying to change sum's value, like you would do in an imperative programming language. However, Standard ML is a functional language and changing values of variables is something you should avoid in functional programming. In fact, when I talk about "variables" in SML, I mean value declarations that cannot be changed. I recommend you to think about your problem a little bit more and maybe you can divide your problem into sub-problems. Good luck.
Im learning Erlang
suppose I have two lists
[{a,a,a,b,c},{d,d,a,a,b},{a,b,c,d,e}]
[{{a,a,a,a,a},10},{{a,a,a,a},6},{{a,a,a},4}]
after Patten Match, expected result {a,a,a,b,c} because it can match {{a,a,a},4}
I tried lists:keysearch and lists:member, but cannot get expected result
any suggestion?
thanks
Matching is not consumptive. Your mental model of how matching works is confusing set operations (like set subtraction and intersection) with comparison and assignment. Your concept of set operations might also benefit from some review.
Erlang's matching is only for assignment and assertion (a sort of comparison). If we match an unbound variable (never used before) against any value, the variable will be bound (assigned) that value:
Foo = {a,b,c}.
Now Foo and {a,b,c} can be used interchangeably. This is pure symbolic assignment like in math class, not a "variable" in the sense of other languages where variables are "storage boxes for values".
If we use the = operator against any value and this now bound symbol Foo, we are doing a check comparison (an assertion) not an assignment. Foo can't mean anything other than {a,b,c} in the current context, so trying to assign it any different value causes an exception, but simply stating that {a,b,c} is {a.b.c} is correct and still yields {a,b,c} (and since Foo is now a symbol for {a,b,c} it can appear on either side and still the statement is correct).
Doing
{a,b,c} = {a,b,c}.
or
{a,b,c} = Foo.
or
Foo = {a,b,c}.
returns {a,b,c}, and does not raise an exception because all we did here was assert that {a,b,c} is indeed {a,b,c}.
If I want just the first value assigned, I can match another way:
{Bar,_,_} = {a,b,c}.
Now Bar represents a, and the _ values are ignored (completely skipped). The original {a,b,c} has not been changed. This is also true if we do:
{_,Baz,_} = Foo.
Now Baz represents b, and Foo still represents {a,b,c}. And that's about it. When it comes to lists, like [{a,b,c}, {1,2,3}] we can still do matching, but because of the nature of lists we will check a piece at a time (try this in the interpreter):
Spam = [{a,b,c}, {1,2,3}].
[Boo | _] = [{a,b,c}, {1,2,3}].
Now Boo represents {a,b,c}, and Spam still represents its original list.
That's about all there is to matching. The magical thing about Erlang's pattern matching is not how it works, its how many places provide natural opportunities for pattern matching, and how this winds up naturally solving a huge number of problems that require procedural checks or direct assignment operations in other languages (cond, function parameters, =, message reception, etc.).
Set and list operations are not the same thing as pattern matching in Erlang. I suggest going through some basic learning material first, like some of the many good beginner tutorials and Learn You Some Erlang.