I have the following Sympy related code in iPython Notebook:
from sympy import *
init_printing()
...
define constants
c, d, e, f = symbols("c, d, e, f")
...
define two matrices
v = Matrix(2,1,[1,1])
w = Matrix(2,1,[2,3])
define symbolic matrices
v, v1, v2 = symbols("v, v1, v2")
v = Matrix(2,1, [v1, v2])
w, w1, w2 = symbols("w, w1, w2")
w = Matrix(2,1, [w1, w2])
addition of symbolic vectors v & w
v + w
results in the following error message
/home/ron/anaconda/lib/python2.7/site-packages/IPython/core/formatters.py:239: FormatterWarning: Exception in image/png formatter:
\left[\begin{smallmatrix}v_{1} + w_{1}\\v_{2} + w_{2}\end{smallmatrix}\right]
^
Expected "\right" (at char 6), (line:1, col:7)
FormatterWarning,
and then produces the correct answer
[v1+w1v2+w2]
The interesting thing is that if I re-execute the cell the error message goes away. I've tried the same code in ipython qtconsole with identical results. Is this a bug or just poor coding on my part?
After further searching I tried the following in the first cell:
from IPython.display import display
from sympy.interactive import printing
printing.init_printing(use_latex='mathjax')
from __future__ import division
import sympy as sym
from sympy import *
This eliminates the above errors so far.
New cell from SymPy: Open Source Symbolic Mathematics on nbviewer
This is a bug, which has been fixed in the git version of SymPy. You can safely ignore it. It will only be an issue if you export your notebook to a format that uses png for the math. If you want to suppress the error entirely, you can use init_printing(use_latex='mathjax').
Related
I'm trying to use the function InterpND from openmdao.components.interp_util.interp.
No problem using it for multidimensional data - I can interpolate a 3-D tensor without problems. However I'd also like to use for 1-D data. Not sure what I am doing wrong, but when I try to do something really simple like
import numpy as np
from openmdao.components.interp_util.interp import InterpND
x = np.array([0.,1.,2.,3.,4.])
y = x**2
f = InterpND(points=x, values=y)
I get the following error message:
ValueError: There are 5 point arrays, but values has 1 dimensions
Looking at the InterpND source code it seems like I SHOULD be able to just have x and y as simple 1-D arrays.
Parameters
----------
points : ndarray or tuple of ndarray of float, with shapes (m1, ), ..., (mn, )
The points defining the regular grid in n dimensions. For 1D interpolation, this
can be an ndarray.
values : array_like, shape (m1, ..., mn, ...)
x is a 1D ndarray, y is also a 1D nd array.
This looks like a bug in OpenMDAO V3.7.0 related to the input error checking. Here is a workaround. If you put the 1-D table points into a list, it works without error:
f = InterpND(points=[x], values=y)
Consider the following code, which is best viewed in a Jupyter notebook, because of the mathematical output the variables a,b,c below contain:
# cell1
import sympy as sp
from sympy import init_printing
init_printing()
u, x = sp.symbols('u x')
f = sp.Function('f')
# cell2: building my function
a = f(x)**2
a
# cell3: doing some stuff to the function
b = a.diff(x).subs([(x,u**2)])
b
# cell4: now I have decided what f should be
c = b.replace(f, lambda x: x**2+x,)
c
but I can't get c to actually symbolically evaluate it, so that I get an expression that doesn't contain a derivative. I have tried everything, simplify, cse etc., nothing seems to work.
Of course I could specify a function at the beginning and then I wouldn't have had this problem. But the thing is I want to keep everything up to b and easily switch functions only at that stage as -for mathematical reasons- it is important for me to view how expression b looks like "abstractly", when I don't have already a concrete function in place, and investigate only afterwards see what happens, when I plug in different concrete functions.
You can use the .doit() method to trigger the evaluation of derivatives:
In [25]: c
Out[25]:
⎛ 4 2⎞ ⎛d ⎛ 2 ⎞⎞│
2⋅⎝u + u ⎠⋅⎜──⎝x + x⎠⎟│ 2
⎝dx ⎠│x=u
In [26]: c.doit()
Out[26]:
⎛ 2 ⎞ ⎛ 4 2⎞
2⋅⎝2⋅u + 1⎠⋅⎝u + u ⎠
Background
I read here that newton method fails on function x^(1/3) when it's inital step is 1. I am tring to test it in julia jupyter notebook.
I want to print a plot of function x^(1/3)
then I want to run code
f = x->x^(1/3)
D(f) = x->ForwardDiff.derivative(f, float(x))
x = find_zero((f, D(f)),1, Roots.Newton(),verbose=true)
Problem:
How to print chart of function x^(1/3) in range eg.(-1,1)
I tried
f = x->x^(1/3)
plot(f,-1,1)
I got
I changed code to
f = x->(x+0im)^(1/3)
plot(f,-1,1)
I got
I want my plot to look like a plot of x^(1/3) in google
However I can not print more than a half of it
That's because x^(1/3) does not always return a real (as in numbers) result or the real cube root of x. For negative numbers, the exponentiation function with some powers like (1/3 or 1.254 and I suppose all non-integers) will return a Complex. For type-stability requirements in Julia, this operation applied to a negative Real gives a DomainError. This behavior is also noted in Frequently Asked Questions section of Julia manual.
julia> (-1)^(1/3)
ERROR: DomainError with -1.0:
Exponentiation yielding a complex result requires a complex argument.
Replace x^y with (x+0im)^y, Complex(x)^y, or similar.
julia> Complex(-1)^(1/3)
0.5 + 0.8660254037844386im
Note that The behavior of returning a complex number for exponentiation of negative values is not really different than, say, MATLAB's behavior
>>> (-1)^(1/3)
ans =
0.5000 + 0.8660i
What you want, however, is to plot the real cube root.
You can go with
plot(x -> x < 0 ? -(-x)^(1//3) : x^(1//3), -1, 1)
to enforce real cube root or use the built-in cbrt function for that instead.
plot(cbrt, -1, 1)
It also has an alias ∛.
plot(∛, -1, 1)
F(x) is an odd function, you just use [0 1] as input variable.
The plot on [-1 0] is deducted as follow
The code is below
import numpy as np
import matplotlib.pyplot as plt
# Function f
f = lambda x: x**(1/3)
fig, ax = plt.subplots()
x1 = np.linspace(0, 1, num = 100)
x2 = np.linspace(-1, 0, num = 100)
ax.plot(x1, f(x1))
ax.plot(x2, -f(x1[::-1]))
ax.axhline(y=0, color='k')
ax.axvline(x=0, color='k')
plt.show()
Plot
That Google plot makes no sense to me. For x > 0 it's ok, but for negative values of x the correct result is complex, and the Google plot appears to be showing the negative of the absolute value, which is strange.
Below you can see the output from Matlab, which is less fussy about types than Julia. As you can see it does not agree with your plot.
From the plot you can see that positive x values give a real-valued answer, while negative x give a complex-valued answer. The reason Julia errors for negative inputs, is that they are very concerned with type stability. Having the output type of a function depend on the input value would cause a type instability, which harms performance. This is less of a concern for Matlab or Python, etc.
If you want a plot similar the above in Julia, you can define your function like this:
f = x -> sign(x) * abs(complex(x)^(1/3))
Edit: Actually, a better and faster version is
f = x -> sign(x) * abs(x)^(1/3)
Yeah, it looks awkward, but that's because you want a really strange plot, which imho makes no sense for the function x^(1/3).
I was trying to do element-wise multiplication of two tensors using the example provided here.
My code:
import torch
x = torch.Tensor([2, 3])
y = torch.Tensor([2, 1])
z = torch.cmul(x, y)
print(z)
It is giving me the following error.
AttributeError: module 'torch' has no attribute 'cmul'
Can anyone tell me why I am getting this error?
I got the solution. Instead of using cmul, I need to use mul. The following code worked for me!
import torch
x = torch.Tensor([2, 3])
y = torch.Tensor([2, 1])
z = torch.mul(x, y)
print(z)
PS: I was using pytorch, not lua.
Because Torch doesnt have this method.
Cmul is a class on its own which is located at torch.legacy.nn which takes Torch as arguments
https://github.com/pytorch/pytorch/blob/master/torch/legacy/nn/CMul.py
try:
z = x.cmul(y)
I think cmul is a method of the class Tensor, not a function...
PS: The exemple in the documentation you gave is written in lua, not python.
I've been working with Sympy for an Interpolation, in which I obtain as a result a 7th degree Polynomial (ax^7 + bx^6 + cx^5 + ...+ h) which I want to Plot, but wen I try to plot it I get errors, for example, if I try:
plt.plot(r,U.subs(x,r))
where r = np.linspace(0,20,num=100) and U = Polynomial(x);
the result is an error message: ValueError: sequence too large; must be smaller than 32, I obtain MemoryError: if I try `r = np.arange(20)'. The only way I could plot it is with a for cycle, substituting one by one and saving it in another variable as a list. So my question is, what is wrong with the first's inputs? is there an easy way to plot a polynomial?
Welcome to SO!
The subs() method is not meant to be used with numpy arrays. lambdify() does what you want. Try:
import numpy as np
import matplotlib.pyplot as plt
import sympy as sy
sy.init_printing() # nice formula rendering in IPython
x = sy.symbols("x", real=True)
# the sample polynomial:
pp = x**3 + 3*x**2 - 6*x - 8
# Convert expression function usable with numpy array:
f_pp = sy.lambdify(x, pp, modules=np)
# Do the plotting:
x_n = np.linspace(-5, 2, 500)
y_n = f_pp(x_n) # evaluate all x_n
fg, ax = plt.subplots(1, 1)
ax.plot(x_n, y_n)
fg.canvas.draw()
plt.show()
The parameter modules=np ensures, that numpy is used for functions in the expression (e.g., sin() => np.sin()). In this example, it is not explicitly needed.
PS: If you include a runnable example in your question, it makes live much easier for potential answerers.