'Two Dimensional Function 3D Plot

I am attempting to plot a two-dimensional function of x and y below in R. I am not good at coding, so it's possible I'm missing something easy, but I got it to work just fine yesterday. It was displaying the 3D plot perfectly and I was even messing with different colors and point sizes for a while with no issues. I save, exit, and then I open the file today and for some reason I am getting an error. I didn't change anything and I have no clue why it won't work now.

library(rgl)
set.seed(27)
x <- runif(100000,-1,1)
y <- runif(100000,-1,1)

## Two-dimensional function of interest
example <- function(x, y){
  f_xy <- x^2 + 2*(y^2) - 0.3*cos(3*pi*x) - 0.4*cos(4*pi*y) + 0.7
  return(f_xy)
}

example(x,y)

plot3d(
  x = x, y = y, z = example(x,y),
  type = "p",
  size = 1.3,
  xlab = "X",
  ylab = "Y",
  zlab = "f(x,y)",
)

I get the following error message:

Error in example(x, y) : 
  dims [product 4] do not match the length of object [100000]

I have narrowed it down to the cosine function being the problem I think. If I mess with

f_xy <- x^2 + 2*(y^2) - 0.3*cos(3*pi*x) - 0.4*cos(4*pi*y) + 0.7

and get rid of the 3pi for x and the 4pi for y then it gives me a plot, but it's obviously not the one I need since I have now changed the equation.

Any ideas on how I can fix this?



Solution 1:[1]

I just figured out how to use cospi(3*x) instead of cos(3*pi*x) and now it works. I honestly have no idea why it worked yesterday without me doing this.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 theGRUMBER