我正在尝试在p5中绘制函数sin(1 / x)。 J的问题是我没有达到我的期望,我得到的是直线而不是正弦函数的波动,对此不胜感激
var y;
var x
function setup() {
createCanvas(windowWidth, windowHeight);
x=-width;
background(0);
angleMode(DEGREES)
}
function draw() {
cord();
y=sin(1/x)
if(x>-510&&x<510)
y=1221550*y
stroke(0,222,0)
strokeWeight(4);
point(x,y);
if(x<width)
x+=1;
stroke(222,2,11)
strokeWeight(2)
line(width,height);
}
function Line(w, h) {
line(-w, 0, w, 0)
line(0, h, 0, -h)
}
function cord() {
translate(width / 2, height / 2);
scale(0.5, -0.5);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.0.0/p5.min.js"></script>
答案 0 :(得分:1)
要记住的一件事是sin
函数的范围是-1.0到1.0。要生成看起来不像直线的正弦波,可以乘以一个倍数以使其具有更大的幅度。
这是一个类似于您的代码的示例,该代码绘制了一个可以看到的正弦波。 请记住,y = 0是屏幕的顶部,因此我添加windowHeight / 2以使波居中。
var y;
var x
function setup() {
createCanvas(windowWidth, windowHeight);
x=0;
background(0);
angleMode(DEGREES)
}
function draw() {
y= (sin(x)* windowHeight/2) + windowHeight/2;
stroke(0,222,0)
strokeWeight(4);
point(x,y);
if(x<width){
x+=1;
} else {
noLoop();
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.8.0/p5.min.js"></script>
现在我们可以绘制x的正弦,我们可以继续绘制1 / x的正弦。首先,我们注意到该函数未在x = 0处定义。通过从x = 1开始避免零,我们可以获得良好的绘图。接下来,我们注意到x为正数时1 / x的正弦将接近零,因为x变大时1 / x将接近零。由于我们知道零的正弦为零,因此我们希望图接近零。
这是一个快速草图,它再次基于您的代码
var y;
var x=1;
function setup() {
createCanvas(windowWidth, windowHeight);
background(0);
angleMode(DEGREES)
}
function draw() {
y= (sin(1/x)* 1000 * windowHeight/2) + windowHeight/2;
stroke(0,222,0)
strokeWeight(4);
point(x,y);
if(x<width){
x+=.1;
} else {
noLoop();
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.8.0/p5.min.js"></script>
现在,我们可以绘制一个草图,同时绘制负值和正值。代替使用x进行角度测量,我们可以使用名为theta的变量作为角度。从上面的实验中我们可以看到,我们最感兴趣的是角度接近但不为零的图。零点时,曲线是不确定的,零点远的地方,曲线非常接近1。
var y;
var x = 0;
function setup() {
createCanvas(windowWidth, windowHeight);
background(0);
angleMode(DEGREES)
}
function draw() {
// here we use the map function to take our x position and turn it into a value between -1 and 1
let theta = map(x, 0, width, -1, 1);
// avoid zero
if (theta !== 0){
// calculate a y based on theta and center the plot in the middle of the window
y= (sin(1/theta) * 1000) + windowHeight/2;
stroke(0,222,0)
strokeWeight(4);
point(x,y);
}
if( x < width){
x+=1;
} else {
noLoop();
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.8.0/p5.min.js"></script>
现在,我们拥有放大至非常接近0并检查振荡行为所需的一切。在这里,我们将theta映射到-0.001至0.001之间的数字
var y;
var x = 0;
function setup() {
createCanvas(windowWidth, windowHeight);
background(0);
angleMode(DEGREES)
}
function draw() {
let theta = map(x, 0, width, -.001, .001);
if (theta !== 0){
y= (sin(1/theta) * 100) + windowHeight/2;
stroke(0,222,0)
strokeWeight(4);
point(x+10,y);
}
if( x < width){
x+=1;
} else {
noLoop();
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.8.0/p5.min.js"></script>
看看sin(1/x) and x sin(1/x) Limit Examples,以更深入地了解此功能的运行情况。