hi guys, I just wanted to plot a graph with Julia, but don’t know how to set interval of the function. the function is (1-cos(x))/x, and x != 0 & x <<1. I tried to write
x = range(0.1, 0.2 , length=100)
y = (1-cos.(x))/x
using Plots
plot(x, y)
but this doesn’t work. can somebody help me how to write x !=0 and x <<1 as an interval?
Use triple-backticks ``` to format code blocks nicely.
The issue you’re running into here is that you’re not broadcasting as many things as you need to be with .
. Either of the below will work:
y = (1 .- cos.(x)) ./ x # add "." to every part manually
y = @. (1 - cos(x)) / x # "@." adds "." to every part automatically
I don’t know what plotting package you’re using so I can’t help with the plot
part, but with the above fix it will probably work anyway.
I don’t understand the part about “x != 0 and x << 1”, but maybe that isn’t a problem after the above changes. If you have questions about that, you’ll probably need to rephrase and ask it again.
Thank you for ur answer first, my question was incomplete. so the function is (1-cos(x))/x, with x !=0 and
|x|<<1, so there is no stated interval, if that makes sense. but I will try again with ur answer. Thank you again
Your approach still works.
x = range(-1, 1, 101) # (Type ?range in REPL to learn about the arguments.)
y = @. (1 - cos(x)) / x
plot(x, y)
Note that zero is excluded from your range because 0/0
is undefined. In Julia (and most other languages) a 0/0
operation becomes NaN
. NaN values are fine to store in your data. They just won’t be plotted. That is why there is a gap in the line plot around zero.
julia> y[51]
NaN
Alternatively, you could just avoid having 0 in your x
vector. Then there won’t be any 0/0
calculations involved.
julia> x = range(-1, 1, 100);
julia> y = @. (1 - cos(x)) / x;
julia> x[50]
-0.010101010101010102
julia> x[51]
0.010101010101010102
julia> plot(x, y)
Finally, note that the plot
function also has a method that will take a function and a range, so you don’t have to bother creating an x
vector and broadcasting it into y
.
julia> f(x) = (1 - cos(x)) / x
f (generic function with 1 method)
julia> plot(f, -1, 1)