I am trying to solve the dispersion equation:
w^2 = k*g * tanh(kh)
I have a vector (25x1 element) input for w and want a vector output for k. I've tried below, but is highly dependent on the tolerance values for uniroot.all:
g = 9.81 #m/s^2
h = 8 #m
w = c(0.1,0.2,0.3) # 3 element vector for ease
dispersion <- function(k) { 0 == k*g*tanh(k*h)^0.5-w }
k1 <- uniroot.all(function(k) dispersion(1e4), c(-10,10), tol = 1e-100, maxiter = 1000)
You can use an apply function, like so:
# Parameters
g <- 9.81
h <- 8
w <- c(0.1, 0.2, 0.3)
# Function to find root of
disp_root <- function(k, w) {k * g * tanh(k * h) - w^2 }
# Apply for each w
res <- sapply(w, function(x)rootSolve::uniroot.all(disp_root, c(-1,1), w = x))
# Repackage results
df_res <- data.frame(w, t(res))
# Fix names
names(df_res)[2:3] <- c("first_root", "second_root")
# Examine results
df_res
#> w first_root second_root
#> 1 0.1 -0.01126658 0.01126658
#> 2 0.2 -0.02272161 0.02272161
#> 3 0.3 -0.03419646 0.03419646
Created on 2020-01-31 by the reprex package (v0.3.0)
Thank you. for completeness it would be (k * g * tanh(k * h))^0.5 - w
Nice to know the
uniroot.all