How does variable name scoping in Maxima work? - scope

I am trying to plot a function test(a) which returns the root of another (in this case x^3-2*x^2+a):
Why does this not work? Why does it work when I change a to x in the last line?

The problem is that mnewton requires an expression which evaluates to a number after assigning values to the specified variables (just x in the example). To make this work, you need to prevent mnewton from being called until a has a value. For example, something like:
plot2d (lambda ([a], rhs(mnewton(p(x, a) = 0, x, 20)[1][1])), [a, -1, 1]);
where p(x, a) is the polynomial expression.
I've made the range of a smaller, since I get an error from mnewton for larger values of a.
You can also try find_root to solve equations of 1 variable.
Since the function is question is a cubic polynomial, there is an exact solution and Maxima can find it via: algsys([p(x, a)], [x]);

Related

How do i Square Root a Function in VBA

I am working on a MonteCarlo simulation model and part of it is to calculate the following formula:
X = Sqr(1-p)Y + Sqr(p)Z,
Where:
Y and Z are randomly obtained values based (idiosyncratic and systematic factors, respectviely) on a standard normal (inv.) distribution, calculated as:
Application.WorksheetFunction.NormInv (Rnd(), mean, sd)
p represents a correlation factor.
My aim is to square root a recalled formula, however when I try the following (inserting the first Sqr), it does not work and gives an error:
Matrix (n, sims) = (R * Sqr(Application.WorksheetFunction.NormInv(Rnd(), mean, sd))) + (Sqr(1 - R) * RandomS(s, x))
where:
R: Correlation factor
RandomS(s,x): generated matrix with Z values.
I don't want to go into too much details about the background and other variables, as the only problem I am getting is with Square Rooting the equation.
Error message I recieve reads:
Run-time error '5':
Invalid procedure call or argument
When I click debug it takes me to the formula, therefore there must be something wrong with the syntax.
Can you help with directly squaring the formula?
Thank you!
Andrew
Square root is simply Sqr.
It works fine in Excel VBA, so for example:
MsgBox Sqr(144)
...returns 12.
Just don't confuse it with the syntax for a worksheet function with is SQRT.
If you're still having an issue with your formula, tit must be with something other than the Square Root function, and I'd suggest you check the values of your variable, and make sure they are properly declared (preferably with Option Explicit at the top of the module).
Also make sure that you're passing Sqr a positive number.
Documentation: Sqr Function
I'm not a math major, but with your formula:
X = Sqr(1-p)Y + Sqr(p)Z,
...you specified how Y and Z are calculated, so calculate them separately to keep it simple:
Dim X as Double, Y as Double, Z as Double
Y = Application.WorksheetFunction.NormInv (Rnd(), mean, sd)
Z = Application.WorksheetFunction.NormInv (Rnd(), mean, sd)
Assuming the comma is not supposed to be in the formula, and having no idea what p is, your final code to calculate X is:
X = Sqr(1-p) * Y + Sqr(p) * Z

Scipy.integrate gives odd results; are there best practices?

I am still struggling with scipy.integrate.quad.
Sparing all the details, I have an integral to evaluate. The function is of the form of the integral of a product of functions in x, like so:
Z(k) = f(x) g(k/x) / abs(x)
I know for certain the range of integration is between tow positive numbers. Oddly, when I pick a wide range that I know must contain all values of x that are positive - like integrating from 1 to 10,000,000 - it intgrates fast and gives an answer which looks right. But when I fingure out the exact limits - which I know sice f(x) is zero over a lot of the real line - and use those, I get another answer that is different. They aren't very different, though I know the second is more accurate.
After much fiddling I got it to work OK, but then needed to add in an exopnentiation - I was at least getting a 'smooth' answer for the computed function of z. I had this working in an OK way before I added in the exponentiation (which is needed), but now the function that gets generated (z) becomes more and more oscillatory and peculiar.
Any idea what is happening here? I know this code comes from an old Fortran library, so there must be some known issues, but I can't find references.
Here is the core code:
def normal(x, mu, sigma) :
return (1.0/((2.0*3.14159*sigma**2)**0.5)*exp(-(x-
mu)**2/(2*sigma**2)))
def integrand(x, z, mu, sigma, f) :
return np.exp(normal(z/x, mu, sigma)) * getP(x, f._x, f._y) / abs(x)
for _z in range (int(z_min), int(z_max) + 1, 1000):
z.append(_z)
pResult = quad(integrand, lb, ub,
args=(float(_z), MU-SIGMA**2/2, SIGMA, X),
points = [100000.0],
epsabs = 1, epsrel = .01) # drop error estimate of tuple
p.append(pResult[0]) # drop error estimate of tuple
By the way, getP() returns a linearly interpolated, piecewise continuous,but non-smooth function to give the integrator values that smoothly fit between the discrete 'buckets' of the histogram.
As with many numerical methods, it can be very sensitive to asymptotes, zeros, etc. The only choice is to keep giving it 'hints' if it will accept them.

Convert Cartesian expression to polar expression using SymPy

Is there a way to convert a Cartesian expression in SymPy to a polar one?
I have the following expression:
1/sqrt(x^2+y^2)
However, I can't seem to get SymPy to acknowledge that this is 1/r in polar coordinates. I tried using the 'subs' command, both of the following options (I imported sympy as asp, and defined all of the symbols earlier):
expr = 1/sp.sqrt(x**2+y**2)
expr.subs((x,y),(r*cos(theta),r*sin(theta))
expr.subs((sp.sqrt(x**2+y**2),sp.atan(y/x)),(r,theta))
but in both cases, I simply receive the original expr again.
Is there a way to convert a Cartesian expression to a polar one in SymPy?
subs((x,y),(r*cos(theta),r*sin(theta))
is not a correct syntax for subs. When multiple symbols are to be replaced, one has to provide either a dictionary
subs({x: r*sp.cos(theta), y: r*sp.sin(theta)})
or an iterable with pairs (old, new) in it:
subs(((x, r*sp.cos(theta)), (y, r*sp.sin(theta))))
The former is more readable; the latter is needed when substitutions must be carried out in a particular order (not the case here).
Either way, to achieve 1/r you also need to declare r as nonnegative
r = sp.symbols('r', nonnegative=True)
and simplify the result of substitution:
expr.subs({x: r*sp.cos(theta), y: r*sp.sin(theta)}).simplify()

Python nomarlization

I have some float numbers like:
586.3212341231,-847.3829941845
I want to use sigmoid function to make the floats in a range of [1,-1] for example :
0.842931342,-0.481238571
Any thoughts about it?
I tried scipy but it gives me wrong outcomes.
There are many such functions: see this Wikipedia link for examples. The graphic there in particular gives examples resulting in your desired range, though the endpoints 1 and -1 are not obtainable for finite values of the parameter x.
The simplest function there is
x / (1 + abs(x))
If you really want your first two sample float numbers to be mapped to your second two float numbers, you can tune your function to be
(a + x) / (b + abs(x))
for particular values of a and b. For two desired values of x and f(x) you can find a and b by solving two simultaneous linear equations. I used sympy to get the following for your sample values:
a = 246.362120860444
b = 401.521207478205
So your final resulting function is
(246.362120860444 + x) / (401.521207478205 + abs(x))
I tested this and it gives just the values you want. Here are two plots showing that this gives your desired range (-1, 1). The first one shows your two points best.

How to filter by predicate on index in Repa

I have two Repa arrays a1 and a2 and I would like to eliminate all the elements in a2 for which the corresponding index in a1 is above a certain threshold. For example:
import qualified Data.Array.Repa as R -- for Repa
import Data.Array.Repa (Z (..), (:.)(..))
a1 = R.fromFunction (Z :. 4) $ \(Z :. x) -> [8, 15, 9, 14] ! x
a2 = R.fromFunction (Z :. 4) $ \(Z :. x) -> [0, 1, 2, 3] ! x
threshold = 10
desired = R.fromFunction (Z :. 2) $ \(Z :. x) -> [0, 2] ! x
-- 15 and 14 are above the threshold, 10
One way to do this is with selectP but I would like to avoid using this, since it computes the arrays, and I would like my arrays to remain in delayed form, if possible.
Another way is with the repa-array, but stack solver does not seem to know how to import this library with resolver nightly-2017-04-10.
One way to look at this issue is that, in order to create a Repa Array, you need to know the size (extent) of the Array upon creation (eg. fromFunction), but, in case of filter operation, there is no way to know the size of the resulting Array in repa without applying a thresholding predicate, essentially computing values of the resulting Array.
Another way to look at it is, Delayed array is a simple function from an index to a value, which is fine for most operations. For filtering though, when you apply a predicate, in order to find a value at a particular index, you now need to know all values that come before that index in the resulting array, cause for any location, a value may be there, maybe not.
vector package solves this issue elegantly with stream fusion, and repa-array, next version of Repa, which is still in experimental stage, seems to be trying to use a similar approach, except with extention to higher dimensions (I might be wrong, haven't looked too closely).
So, short answer, there is no way to do filtering with Repa style functional fusion. Either:
stick to selectP - faster (probably), but less memory efficient (for sure), or
piggy back onto ifilter from vector package for sequential
filtering
You can build a list of pairs with zip, then filter by a predicate function with the type (Int,Int) -> Bool and lastly extract the first or second element of the pair (depending on which one you want) by using map fst or map snd respectively. Everything you need for this is in Prelude.
I hope this is enough information so you can put the pieces together yourself. If in doubt, look at the type signatures of the functions i mentioned.

Resources