Reputation: 31985
I would like to depict a graph that is the power of some values in a continuous way.
f <- function(x) {
return (x^(1/3))
}
ggplot(data.frame(x=seq(-5,5,length.out=10)), aes(x)) +
stat_function(fun=f)
This only shows the values that are x > 0
, though if I use online graph tool desmos it shows values of x < 0
too. In interactive sessions, -3^(1/3)
returns -1.44225
.
Why does R omit it and how can I depict the negative x values too?
Upvotes: 2
Views: 130
Reputation: 174378
The fractional power of a negative number is a complex number. If you want to include these in your plot, you could show the imaginary and real components separately:
real_part <- function(x) {
Re(complex(length(x), x, 0)^(1/3))
}
imaginary_part <- function(x) {
Im(complex(length(x), x, 0)^(1/3))
}
We can plot with labels for clarity:
library(geomtextpath)
#> Loading required package: ggplot2
ggplot(data.frame(x = seq(-5, 5, length.out = 10)), aes(x)) +
stat_function(fun = real_part, aes(label = "Real part"), geom = "textpath",
hjust = 0.8, vjust = -0.2, size = 6) +
stat_function(fun = imaginary_part, color = "red", linetype = 2, hjust = 0.2,
aes(label = "Imaginary part"), geom = "textpath", vjust = -0.2,
size = 6) +
theme_minimal(base_size = 20)
Created on 2022-11-20 with reprex v2.0.2
Upvotes: 3
Reputation: 17204
As @JohnColeman explains, the results of your function are undefined for negative x
. The reason -3^(1/3)
seems to work in the console but not your functions is due to operator precedence. ^
has higher precedence in R than -
, so your console input is evaluated as:
-(3^(1/3))
# -1.44225
But when you pass -3
to your function, it's evaluated as:
(-3)^(1/3)
# NaN
Upvotes: 3
Reputation: 52008
Exponential functions with a negative base are considered undefined over the set of real numbers. This is since e.g. (-2)^(m/n)
is impossible if n
is even and given any x
there will be infinitely many fractions of that form which are arbitrarily close to x
. If you want the cube root you can use
cuberoot <- function(x){sign(x)*abs(x)^(1/3)}
Upvotes: 3