I'd like to plot a surface in Julia, but using this syntax:
f(x)=x[1]-x[2]
not
f(x,y)=x-y
Could you help me do that?
In this case the simplest approach is to use a wrapper anonymous function:
(x...) -> f(x)
that you can pass to the plotting function instead of your original function.
Now you have:
julia> f(x)=x[1]-x[2]
f (generic function with 1 method)
julia> ((x...) -> f(x))(100, 5)
95
Related
I was trying to plot complex numbers in Julia but I haven't found any good way to do it yet.
using PyPlot
nums = ComplexF64.([1,2,4],[2,2,-1])
polar.(Base.vect.(0.0,angle.(nums)),Base.vect.(0.0,abs.(nums)),marker="o")
One way is to plot the real and imaginary part as x and y
julia> using Plots
julia> d = [0.0000000+0.0000000im, 0.1111111+0.0000000im,
0.1666667+0.0962250im, 0.2222222+0.0000000im,
0.3333333+0.0000000im, 0.3888889+0.0962250im,
0.3333333+0.1924501im, 0.4444444+0.1924501im,
0.5000000+0.2886751im, 0.5555556+0.1924501im,
0.6666667+0.1924501im, 0.6111111+0.0962250im,
0.6666667+0.0000000im, 0.7777778+0.0000000im,
0.8333333+0.0962250im, 0.8888889+0.0000000im,
1.0000000+0.0000000im]
julia> plot(real(d),imag(d))
# or directly with plot(d)
Heres a block of code that plots a function over a range, as well as the at a single input :
a = 1.0
f(x::Float64) = -x^2 - a
scatter(f, -3:.1:3)
scatter!([a], [f(a)])
i would like to plot the line, tangent to the point, like so:
Is there a pattern or simple tool for doing so?
That depends on what you mean by "pattern or simple tool" - the easiest way is to just derive the derivative by hand and then plot that as a function:
hand_gradient(x) = -2x
and then add plot!(hand_gradient, 0:0.01:3) to your plot.
Of course that can be a bit tedious with more complicated functions or when you want to plot lots of gradients, so another way would be to utilise Julia's excellent automatic differentiation capabilities. Comparing all the different options is a bit beyond the scope of this answer, but check out https://juliadiff.org/ if you're interested. Here, I will be using the widely used Zygote library:
julia> using Plots, Zygote
julia> a = 1.0;
julia> f(x) = -x^2 - a;
[NB I have slightly amended your f definition to be in line with the plot you posted, which is an inverted parabola]
note that here I am not restricting the type of input argument x to f - this is crucial for automatic differentiation to work, as it is implemented by runnning a different number type (a Dual) through your function. In general, restricting argument types in this way is an anti-pattern in Julia - it does not help performance, but makes your code less interoperable with other parts of the ecosystem, as you can see here if you try to automatically differentiate through f(x::Float64).
Now let's use Zygote to provide gradients for us:
julia> f'
#43 (generic function with 1 method)
as you can see, running f' now returns an anonymous function - this is the derivative of f, as you can verify by evaluating it at a specific point:
julia> f'(2)
-4.0
Now all we need to do is leverage this to construct a function that itself returns a function which traces out the line of the gradient:
julia> gradient_line(f, x₀) = (x -> f(x₀) + f'(x₀)*(x-x₀))
gradient_line (generic function with 1 method)
this function takes in a function f and a point x₀ for which we want to get the tangent, and then returns an anonymous function which returns the value of the tangent at each value of x. Putting this to use:
julia> default(markerstrokecolor = "white", linewidth = 2);
julia> scatter(f, -3:0.1:3, label = "f(x) = -x² - 1", xlabel = "x", ylabel = "f(x)");
julia> scatter!([1], [f(1)], label = "", markersize = 10);
julia> plot!(gradient_line(f, 1), 0:0.1:3, label = "f'(1)", color = 2);
julia> scatter!([-2], [f(-2)], label = "", markersize = 10, color = 3);
julia> plot!(gradient_line(f, -2), -3:0.1:0, label = "f'(-2)", color = 3)
It is overkill for this problem, but you could use the CalculusWithJulia package which wraps up a tangent operator (along with some other conveniences) similar to what is derived in the previous answers:
using CalculusWithJulia # ignore any warnings
using Plots
f(x) = sin(x)
a, b = 0, pi/2
c = pi/4
plot(f, a, b)
plot!(tangent(f,c), a, b)
Well, the tool is called high school math :)
You can simply calculate the slope (m) and intersect (b) of the tanget (mx + b) and then plot it. To determine the former, we need to compute the derivative of the function f in the point a, i.e. f'(a). The simplest possible estimator is the difference quotient (I assume that it would be cheating to just derive the parabola analytically):
m = (f(a+Δ) - f(a))/Δ
Having the slope, our tanget should better go through the point (a, f(a)). Hence we have to choose b accordingly as:
b = f(a) - m*a
Choosing a suitably small value for Δ, e.g. Δ = 0.01 we obtain:
Δ = 0.01
m = (f(a+Δ) - f(a))/Δ
b = f(a) - m*a
scatter(f, -3:.1:3)
scatter!([a], [f(a)])
plot!(x -> m*x + b, 0, 3)
Higher order estimators for the derivative can be found in FiniteDifferences.jl and FiniteDiff.jl for example. Alternatively, you could use automatic differentiation (AD) tools such as ForwardDiff.jl to obtain the local derivative (see Nils answer for an example).
To demonstrate, let's start with a simple multi-variable function f(x,y) = xy^2.
I am trying to find a command that would allow me to numerically integrate f(2, y) = 2y^2 from y = 0 to y = 2. (i.e. the original function is multi-variable, but only one variable remains when actually doing the integration)
I needed to define the function that way as I need to obtain the results using different values of x. (probably going to involve for-loop, but that is another story)
I have tried to walk through Cubature's user guide but apparently did not find anything useful. Maybe I have missed it
Can anyone help?
In such case it is simplest to use an anonymous function wrapper:
using QuadGK
f(x,y) = x*y^2
intf(x) = quadgk(y -> f(x, y), 0, 2)
if the anonymous function would be longer you could write:
intf(x) = quadgk(0, 2) do y
f(x, y)
end
This is an exact equivalent of the latter but do syntax allows you to write longer bodies of an anonymous function.
Now you can write e.g.:
julia> intf(1)
(2.6666666666666665, 4.440892098500626e-16)
julia> intf(2)
(5.333333333333333, 8.881784197001252e-16)
julia> intf(3)
(8.0, 0.0)
Consider this minimal example
julia> using Plots
julia> pyplot()
julia> x = -100:0.01:100
julia> y = x
julia> plot(x, y, xscale = :log10)
This raises the following error:
DomainError:
log10 will only return a complex result if called with a complex argument. Try log10(complex(x)).
Of course, this is because the logarithm of negative numbers is not well defined. However, in python you can overcome this problem using the command plt.xscale('symlog'). Is there an equivalent command for Plots.jl?
Help! I got a result in the form of sym. But it seems eval doesn't work. How can I get a numerical answer? Thanks.
#show BBias
#show eval(BBias)
#show typeof(eval(BBias))
BBias = -213.53387843501*cos(6) + 73.4119295548356*sin(6) - 50*sin(6)*cos(6) + 316.255048160247
eval(BBias) = -213.53387843501*cos(6) + 73.4119295548356*sin(6) - 50*sin(6)*cos(6) + 316.255048160247
typeof(eval(BBias)) = SymPy.Sym
What you have here is a symbolic SymPy expression, not a Julia expression. eval in Julia will only evaluate a Julia expression. The N function from SymPy will evaluate and expression down to it's floating point value.
You can do a typeof(BBias) to see what kind of an object this is. Since I don't know how you have generated that object, I cannot replicate it fully. But here is some simple example showing how to using SymPy from Julia
julia> using SymPy
julia> x=Sym("pi")
pi
julia> typeof(x)
SymPy.Sym
julia> y=sin(x)
0
julia> typeof(y)
SymPy.Sym
julia> typeof(eval(y))
SymPy.Sym
julia> z=N(y)
0
julia> typeof(z)
Int64
A detailed tutorial on using SymPy from Julia is available here: http://nbviewer.jupyter.org/github/jverzani/SymPy.jl/blob/master/examples/tutorial.ipynb