Printing help? information from a function in Julia - julia

Title summarises it pretty well. Is there a simple way to remotely display the help information for a function?
DispHelp = function(query_string)
# Enter help mode as you would by pressing `?` and query the given string
print(help_text)
return help_text
end
Any thoughts?

Might be possible.
julia-1.2> for f in [sin, cos, tan]
println(Base.doc(f))
end
```
sin(x)
```
Compute sine of `x`, where `x` is in radians.
```
sin(A::AbstractMatrix)
```
Compute the matrix sine of a square matrix `A`.
If `A` is symmetric or Hermitian, its eigendecomposition ([`eigen`](#ref)) is used to compute the sine. Otherwise, the sine is determined by calling [`exp`](#ref).
# Examples
```jldoctest
julia> sin(fill(1.0, (2,2)))
2×2 Array{Float64,2}:
0.454649 0.454649
0.454649 0.454649
```
```
cos(x)
```
Compute cosine of `x`, where `x` is in radians.
```
cos(A::AbstractMatrix)
```
Compute the matrix cosine of a square matrix `A`.
If `A` is symmetric or Hermitian, its eigendecomposition ([`eigen`](#ref)) is used to compute the cosine. Otherwise, the cosine is determined by calling [`exp`](#ref).
# Examples
```jldoctest
julia> cos(fill(1.0, (2,2)))
2×2 Array{Float64,2}:
0.291927 -0.708073
-0.708073 0.291927
```
```
tan(x)
```
Compute tangent of `x`, where `x` is in radians.
```
tan(A::AbstractMatrix)
```
Compute the matrix tangent of a square matrix `A`.
If `A` is symmetric or Hermitian, its eigendecomposition ([`eigen`](#ref)) is used to compute the tangent. Otherwise, the tangent is determined by calling [`exp`](#ref).
# Examples
```jldoctest
julia> tan(fill(1.0, (2,2)))
2×2 Array{Float64,2}:
-1.09252 -1.09252
-1.09252 -1.09252
```
With Julia you can read the code for everything, so a few hours looking through the source should lead to enlightenment.

To complete the daycaster's answer on how to display the help for built-in function.
If you want to display help on your own function, you have to write a doc string as follow, on this example function:
#Here is my docstring between triple quote, just before function declaration
"""
square(x)
Return the square of x, if it's a number. If it's a vector, return element-wise square of the vector
"""
function square(x)
#And now the body of my function
out = x.*x
end

Related

Print a docstring of a program to stdout in Julia

Julia accepts ?sin on the command line to display a help text. I believe such help texts are implemented as docstrings. I would like to print such docstrings from my Julia program at runtime. How to do that?
julia> #doc sin
sin(x)
Compute sine of x, where x is in radians.
sin(A::AbstractMatrix)
Compute the matrix sine of a square matrix A.
If A is symmetric or Hermitian, its eigendecomposition (eigen) is used to compute the
sine. Otherwise, the sine is determined by calling exp.
Examples
≡≡≡≡≡≡≡≡≡≡
julia> sin(fill(1.0, (2,2)))
2×2 Matrix{Float64}:
0.454649 0.454649
0.454649 0.454649

Converting R function to Latex formula

I'm having trouble converting an R function to a latex formula. I have a df (m) of x and y coordinates that I then calculate a centroid from using the following R function:
cnt = c(mean(m[,1]),mean(m[,2]))
I then take that same list and calculate the distance from each x,y pair to that centroid. Lastly, I then take the mean distance over all the records from the centroid using the following code:
mean_distance <- mean(apply(m,1,function(x,cnt) {(sqrt((x[1] - cnt[1])^2+(x[2]-cnt[2])^2))},cnt))
I think I got the first part figured out (finding the centroid coordinates)
cnt\left(x, y\right) = \frac{\sum x_{i}}{n}, \frac{\sum y_{i}}{n}
I'm having trouble with the second calculation. I'm new to latex and would like to create (an elegant) formula to include in a paper I am writing. Is there any easy way to convert this R code to latex?
You can try something like
$$
C(x,y) = (C_1, C_2) = \left( \frac1n\sum_{i=1}^n x_i,\frac1n\sum_{i=1}^n y_i\right)
$$
$$
d = \frac1n \sum_{i=1}^n \sqrt{\left( x_i-C_1\right)^2+\left( y_i-C_2\right)^2}
$$
if I understood what you want.

Plot of function, DomainError. Exponentiation yielding a complex result requires a complex argument

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).

Julia: Syntax for indexing into an n-dimensional array without fixing n

I'm trying to use Julia's Interpolations package to interpolate a function sampled on an n-dimensional grid. The Interpolations package uses a syntax similar to array indexing for specifying the point at which to interpolate the data (in fact it appears that the Interpolations package imports the getindex function used for array indexing from Base). For example for n=2 the following code:
using Interpolations
A_grid = [1 2; 3 4]
A = interpolate((0:1, 0:1), A_grid, Gridded(Linear()))
a = A[0.5, 0.5]
println(a)
prints the result of a linear interpolation at the midpoint (0.5, 0.5).
Now, if I have an n-dimensional vector (e.g. index_vector = [0.5, 0.5] in n=2 dimensions), I see that I can get the same result by writing
a = A[index_vector[1], index_vector[2]]
but I am unable to do this in general. That is, I would like to find/write a function that takes an n-dimensional array A and a vector index_vector of length n and returns
A[index_vector[1], ... , index_vector[n]]
where n is not known beforehand. Is there a way to do this when the entries of index_vector are not necessarily integers?
I think you can use the splat (...) for that. ... "distributes" the elements of a collection to argument slots:
using Interpolations
A_grid = [1 2; 3 4]
A = interpolate((0:1, 0:1), A_grid, Gridded(Linear()))
index_vector = [0.5, 0.5]
a = A[index_vector...]
println(a)
gives the same result of your example.

Returning all the x coordinates where the graph cuts a y coordinate

I've got the first line down which is defining the function:
f <- function(x) 3034*log(x)+2305.84*log(1-x)-1517*log(1-x)
Now the problem I'm having is I need to find all the x values where
f(x)=-1947.92 but I've got no idea what the command is to do this?
Normally I would say you should use uniroot(), after modifying the function to return zero at the target, but that will be problematic here:
target <- -1947.92
f <- function(x) 3034*log(x)+2305.84*log(1-x)-1517*log(1-x)
g <- function(x) f(x)-target
uniroot(g,interval=c(1e-4,1-1e-4))
## Error in uniroot(g, interval = c(1e-04, 1 - 1e-04)) :
## f() values at end points not of opposite sign
What's going on is that your curve crosses zero in two places. uniroot() requires that you bracket the root:
Let's take a look:
curve(g(x))
abline(h=0,col=2)
Zoom in:
curve(g(x),from=0.75,to=0.85)
abline(h=0,col=2)
Now we can either just eyeball this (i.e. use interval=c(1e-4,0.8) or interval=c(0.8,1-1e-4) depending on which root we're interested in) or find
opt1 <- optim(g,par=0.5,method="L-BFGS-B",lower=1e-4,upper=1-1e-4,
control=list(fnscale=-1)) ## maximize rather than min
then use opt1$par as your cut-point. (Or you could do some simple calculus: the maximum [point where the derivative wrt x is zero] is much easier to compute than the roots ...)
Alternatively, you could ask Wolfram Alpha ...

Resources