Sympy: Howto to rewrite erf function - sympy

I have an expression in SymPy that involves the normal cumulative function, N(x) which is directly linked to the error function through the equation N(x)=0.5*erf(x/sqrt(2)) + 0.5.
When I use the Normal(0,1).cdf(x) function of SymPy, it is written using the error function. So, when I output latex string of some (complicated) expression, the seem more complicated when using erf (instead of N(x), it outputs the equation mentionned obove). I tried to define a symbol N=0.5*erf(x/sqrt(2)) + 0.5 and tried the command 'rewrite' the rewrite my expression in terms of N, but 'rewrite' seems to work only with internally defined functions.
Does any bodu know how to rewrite erf(some_expression) in terms of N(some_expression), given that I don't know some_expression in advance (can't use subs) ?
Thanks in advance

I take it from your question that you are using Normal from sympy.statistics. You should move to sympy.stats. sympy.statistics has been deprecated for some time, and will be removed in the next version of SymPy.
To answer your question more directly, you can replace functions with functions using replace, like expr.replace(erf, lambda x: (N(x) - 0.5)/0.5).
The problem here is that there is no function N. I would expect this to be done better in sympy.stats, where the distributions are represented symbolically. However, I didn't find a way to do it. I opened https://github.com/sympy/sympy/issues/7819 for this.

Related

How to change printed representation of function's derivative in sympy

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.

Using Brent algorithm to find the root of a function f with an initial guess, but without intervals [a,b] s.t. f(a)f(b)<0

I would like to know how to use Brent algorithm if no opposite signs can be provided.
For example, in the C++ library of Brent algorithm, the root-finding procedure that implements Brent’s method has to be used, following the header file, in the form of
double zero ( double a, double b, double t, func_base& f );
where a, b satisfies the condition of opposite signs: f(a).f(b) < 0
In my problem setting, I need to find the root(s) of a black-box function f. An initial guess is provided but no endpoints a,b, such that f(a) f(b)<0 are provided It seems that in Matlab there is a function fmin that only needs an initial guess. I would like to know how to do this using C++, in particular, using the implementation of Brent such as the one linked above?
Thanks for your ideas.
Without doing exhaustive search (and in the case of real valued function, you cannot, since the value of x is uncountable), there is no way to really guarantee finding the root if such exist.
One heuristic approach to address the problem is using gradient descent, in order to minimze (/maximize) the value of the function, until you find a local minimum (/maximum) or until you find a root.
The problem with this approach is you can get stuck in a local minimum (/maximum) before finding the root, and "think" there is no root, even if one does exist.
Under the assumptions that
f is a black-box, i.e. it can be evaluated but no information on its shape is known whatsoever.
You have to use a method that requires a priori knowledge of an interval [a,b] which brackets a root of f (assuming f is continuous).
I think your only option is to make a preliminary search for two valid points a and b.
This can be done in a number of ways. The most simple-minded could be to run a linear search (with some prescribed step) starting from your initial guess, which can be repeated with a finer step if it turns out unsuccessful. If f is not too "weird" a simple method should do.
Clearly, some basic clue on the properties of f is always necessary, for example that it actually has a root and that it is continuos, differentiable, etc.. All root finding methods (gradient descent, Newton-Raphson, bisection, etc.) assume some basic properties of the function.

Why is SymPy's solver returning only one, trivial solution?

I want to find all the real numbers that satisfy a particular equation. I have no trouble finding these values in Mathematica with
Solve[n*9^5 == 10^n-1, n]
which gives both 0 and 5.51257; but when I use SymPy's (0.7.3; Python 2.7.5) solve
n = sympy.symbols('n')
sympy.solve(n*9**5 - 10**n-1, n)
I seem to only get something that looks like 0, and not the second value, which is what I'm really seeking.
How can I get SymPy to produce the non-trivial solution I'm looking for? Is there a different function or package I should be using instead?
solve only gives symbolic solutions, so if it cannot find a closed form for a solution, it will not return it. If you only care about numeric solutions, you want in SymPy is nsolve, or you can use a more numerical oriented Python library. For example
sympy.nsolve(n*9**5 - 10**n-1, n, 5)
will give you the solution you are looking for.
The problem with using solve is that there are infinitely many solutions, each corresponding to a branch of the LambertW function. See WolframAlpha for the full solution set. Unfortunately, only the principal branch of LambertW is implemented in SymPy.
Until this is fixed, another way to fix the issue would be to manually evaluate the LambertW returned by solve on another branch, using mpmath.lambertw. The easiest way to do this is with lambdify:
s = sympy.solve(n*9**5 - 10**n-1, n)
import sympy.mpmath
# Replace -1 with any integer. -1 gives the other real solution, the one you want
lambdify([], s, [{'LambertW': lambda x: sympy.mpmath.lambertw(x, -1)}, "mpmath"])()
This gives [mpf('5.5125649309411875')].
The dictionary tells lambdify to evaluate the LambertW function using the -1 branch, using mpmath. The "mpmath" tells it to use mpmath for any other functions that may be in the solution.

Writing INTEGRATOR similar to http://integrals.wolfram.com/index.jsp using parsing in java

Hi as part of my project I have been working on evaluation of arithmetic expression using reg-ex in java.
expressions are like this : 2+3/4(5+7)
first I will modify it to this : 2+3/4*(5+7)
and convert it to postfix
postfix: 23457+*/+
The procedure I have adopted is parsing all of the tokens (i.e. Integers,Operators,Open Paren,Close Paren) using Reg-Ex and then sorting by the i-th position of their occurrence. After that I converted that array of token into post-fix expression and then solved that expression, Until this point every thing is working fine.
Now I would like to extend it to solving differentiation,integration or solving quadratic equation.
foe ex: differentiate or integrate expression x^2+2*x+2
similar to http://integrals.wolfram.com/index.jsp
Is it possible? because right now I dont have any clue how to proceed with that?
Most calculators I am aware of - calculating equations/differentions and integrals using numerical analysis. This allows one to find a close solution to the exact (analytical one) solution, sometimes even for unsolveable equations (This is how we got the standard normal table, for the unsolveable normal density function)
For example, solving integrals - gaussian quardature is very common and efficeint way.
For solving equations - regula-falsi method is a simple and intuitive one
I think that most integral computation engines use the numerical approach just as amit said, however there's a way to compute it symbolically, but it's heuristic more than algorithmic, it's done by pattern matching. I think that Mathematica follows this approach.

calculating user defined formulas (with c++)

We would like to have user defined formulas in our c++ program.
e.g. The value v = x + ( y - (z - 2)) / 2. Later in the program the user would define x,y and z -> the program should return the result of the calculation. Somewhen later the formula may get changed, so the next time the program should parse the formula and add the new values. Any ideas / hints how to do something like this ? So far I just came to the solution to write a parser to calculate these formulas - maybe any ideas about that ?
If it will be used frequently and if it will be extended in the future, I would almost recommend adding either Python or Lua into your code. Lua is a very lightweight scripting language which you can hook into and provide new functions, operators etc. If you want to do more robust and complicated things, use Python instead.
You can represent your formula as a tree of operations and sub-expressions. You may want to define types or constants for Operation types and Variables.
You can then easily enough write a method that recurses through the tree, applying the appropriate operations to whatever values you pass in.
Building your own parser for this should be a straight-forward operation:
) convert the equation from infix to postfix notation (a typical compsci assignment) (I'd use a stack)
) wait to get the values you want
) pop the stack of infix items, dropping the value for the variable in where needed
) display results
Using Spirit (for example) to parse (and the 'semantic actions' it provides to construct an expression tree that you can then manipulate, e.g., evaluate) seems like quite a simple solution. You can find a grammar for arithmetic expressions there for example, if needed... (it's quite simple to come up with your own).
Note: Spirit is very simple to learn, and quite adapted for such tasks.
There's generally two ways of doing it, with three possible implementations:
as you've touched on yourself, a library to evaluate formulas
compiling the formula into code
The second option here is usually done either by compiling something that can be loaded in as a kind of plugin, or it can be compiled into a separate program that is then invoked and produces the necessary output.
For C++ I would guess that a library for evaluation would probably exist somewhere so that's where I would start.
If you want to write your own, search for "formal automata" and/or "finite state machine grammar"
In general what you will do is parse the string, pushing characters on a stack as you go. Then start popping the characters off and perform tasks based on what is popped. It's easier to code if you force equations to reverse-polish notation.
To make your life easier, I think getting this kind of input is best done through a GUI where users are restricted in what they can type in.
If you plan on doing it from the command line (that is the impression I get from your post), then you should probably define a strict set of allowable inputs (e.g. only single letter variables, no whitespace, and only certain mathematical symbols: ()+-*/ etc.).
Then, you will need to:
Read in the input char array
Parse it in order to build up a list of variables and actions
Carry out those actions - in BOMDAS order
With ANTLR you can create a parser/compiler that will interpret the user input, then execute the calculations using the Visitor pattern. A good example is here, but it is in C#. You should be able to adapt it quickly to your needs and remain using C++ as your development platform.