In Mathematica, it is possible to prevent the system from simplifying expressions when they are entered. The syntax is as follows:
HoldForm[x/x]
Is it possible to do something similar with SymPy?
The following approaches achieve a similar effect. There might be others available I am not aware of.
import sympy as sp
x = sp.symbols('x')
expr1 = x/x
expr2 = sp.S('x/x', evaluate=False)
expr3 = sp.Mul(x, 1/x, evaluate=False)
print(expr1)
print(expr2)
print(expr3)
1
x/x
x/x
You can also use with evaluate(False), like
with evaluate(False):
print(x/x)
Related
Here is my problem.
I'm using sympy and a complex matrix P (all elements of P are complex valued).
I wanna extract the real/imaginary part of the first row.
So, I use the following sequence:
import sympy as sp
P = sp.Matrix([ [a+sp.I*b,c-sp.I*d], [c-sp.I*d,a+sp.I*b] ])
Row = P.row(0)
Row.as_mutable()
Re_row = sp.re(Row)
Im_row = sp.im(Row)
But the code returns me the following error:
"AttributeError: ImmutableMatrix has no attribute as_coefficient."
The error occurs during the operation sp.re(Row) and sp.im(Row)...
Sympy tells me that Row is an Immutable matrix but I specify that I want a mutable one...
So I'm in a dead end, and I don't have the solution...
Could someone plz help me ?
thank you very much !
Most SymPy functions won't work if you just pass a Matrix to them directly. You need to use the methods of the Matrix, or if there is not such method (as is the case here), use applyfunc
In [34]: Row.applyfunc(re)
Out[34]: [re(a) - im(b) re(c) + im(d)]
In [35]: Row.applyfunc(im)
Out[35]: [re(b) + im(a) -re(d) + im(c)]
(I've defined a, b, c, and d as just ordinary symbols here, if you set them as real the answer will come out much simpler).
I'm working on a project. Currently I have a fairly large conditional statement, that assigns a value to a variable based on some input parameters. So, I have something like this.
if some condition
x = some value
elsif another condition
x = a different value
...
What's the best way to refactor this? I'm hoping that I might end up with something like
x = some value if some condition || another value if another condition
Is there a pattern for this sort of thing?
Just put the assignment outside the if.
x = if some condition
some value
elsif another condition
a different value
Or you could use a Hash.
x = dict[some condition]
It's not a pattern, but an operator. The one you're referring to is the ternary operator:
If Condition is true ? Then value X : Otherwise value Y
Here is an example:
speed = 90
speed > 55 ? puts("I can't drive 55!") : puts("I'm a careful driver")
Using the ternary statement is short, sweet, and does the job.
x = some condition ? some value :
another condition ? a different value : ...
A conditional statement is also an expression, so one of the first things you can do, if the variable is the same in each condition, is:
x = if cond1
expr1
elsif cond2
expr2
....
end
If the conditions are all states of a single expression, you can make this even neater, using a case statement.
However, the next most obvious re-factoring exercise is to get the big conditional isolated into a method, which should be fed the bare minimum data required to evaluate all the conditions and expressions.
E.g.
# Where conditional is currently, and x assigned, assuming the conditionals
# need a couple of variables . . .
x = foo param1, param2
# Elsewhere
private
def foo p1, p2
if cond1
expr1
elsif cond2
expr2
....
end
end
If you want to refactor for code clarity and flexibility, consider the replacing conditional with polymorphism refactor.
There's not enough detail in your question to go much further with recommendations, but this refactor will make your code base much more resistant to change. If you receive a new requirement, it's bad form to break open the conditional and modify it (more prone to introducing bugs, more difficult to do); it's preferable to create a new object that you can plug into the existing codebase. This flexibility what the Open/Closed Principle (the "O" in the SOLID acronym) describes.
I would like to know if it is possible to evaluate a table of functions at a point in mathematica.
Right now I am given a table of 10 functions and would like to evaluate them at x = 0.
I tried this :
Evaluate[myTable, {x, 0}]
And it does not evaluate anything, it just gives this output:
Sequence[ {term1, term2, term3, term4, term5, term6, term7, term8, term9, term10}, {x,0}]
Replacing term1 ... term10 with the actual terms.
How would I be able to do this?
Thanks,
Bucco
Through[{f1,f2,f3,f4,f5,f6,f7,f8,f9,10}[0]]
In my Mathematica program, I do some entropy calculations and I want to use this convention: Log[0]*0 = 0. Is there a clean way to do it or I have to write my own function?
Inspired by http://tinyurl.com/9d8r4rt I tried things like this:
Unprotect[Times];
Times[0, -Infinity] := 0;
Protect[Times];
But it doesn't seem to work in my case. Is there an elegant way to do this?
I support High Performance Mark's statement above. Nevertheless this is an interesting question because the answer is nontrivial.
You would need:
Unprotect[DirectedInfinity];
DirectedInfinity /: Log[0] 0 := 0
You need DirectedInfinity because:
Log[0] // FullForm
DirectedInfinity[-1]
And you need an UpValue, made using TagSet, to override the default reaction to -∞ * 0, because UpValues are tried before other definitions.
I would like to pass the parameter values in meters or kilometers (both possible) and get the result in meters/second.
I've tried to do this in the following example:
u = 3.986*10^14 Meter^3/Second^2;
v[r_, a_] := Sqrt[u (2/r - 1/a)];
Convert[r, Meter];
Convert[a, Meter];
If I try to use the defined function and conversion:
a = 24503 Kilo Meter;
s = 10198.5 Meter/Second;
r = 6620 Kilo Meter;
Solve[v[r, x] == s, x]
The function returns the following:
{x -> (3310. Kilo Meter^3)/(Meter^2 - 0.000863701 Kilo Meter^2)}
which is not the user-friendly format.
Anyway I would like to define a and r in meters or kilometers and get the result s in meters/second (Meter/Second).
I would be very thankful if anyone of you could correct the given function definition and other statements in order to get the wanted result.
Here's one way of doing it, where you use the fact that Solve returns a list of rules to substitute a value for x into v[r, x], and then use Convert, which will do the necessary simplification of the resulting algebraic expression as well:
With[{rule = First#Solve[v[r,x]==s,x]
(* Solve always returns a list of rules, because algebraic
equations may have multiple solutions. *)},
Convert[v[r,x] /. rule, Meter/Second]]
This will return (10198.5 Meter)/Second as your answer.
You just need to tell Mathematica to simplify the expression assuming that the units are "possitive", which is the reason why it doesn't do the simplifications itself. So, something like
SimplifyWithUnits[blabla_, unit_List]:= Simplify[blalba, (#>0)&/#unit];
So if you get that ugly thing, you then just type %~SimplifyWithUnits~{Meter} or whatever.