As one variable decreases another one increases - javascript

I have the following math problem inside JavaScript.
The problem: As x decreases, I need y to decrease proportionately to x as y approaches 0%.
And so when x = 0%, y = 0%.
<script type="text/javascript">
x = 0.50;
y = 0.30;
if (x < 0.50){
// set y here somehow to gradually increase
}
</script>

Change in y would be 0.6 times the change in x (assuming you want y to decrease linearly from 0.3 to 0.0 as x decreases from 0.5 to 0.0):
if (x < 0.50)
{
y = 0.3 - 0.6*x;
}

Related

Exponential Graph Animation P5js Canvas

I am trying to animate a growing exponential graph using P5js.
I have successfully plotted the graph itself, but the "rulers/scales" on the sides won't work.
I want the "window" to scale according to the X and Y axis, just like this example: Animation I am trying to replicate this animation
I want the graph to "grow" and the rulers/scales on the sides to represent the growth, X is time and Y the multiplier (big text in the middle). As seen on the animation I linked, X and Y values move towards the origin after the graph has gone outside the box.
Link to P5 editor with code: P5 web editor
There is at least one big error in
scaleLevel -= 0.1;
because this way it gets zero and you will divide by it within REscale.
Your intention is to draw some exponential function f(x) in the interval 0 to x. The value of x is increasing by time. The value of the exponential function is also rising but with another rate. So you will have to use two separate scale factors: sX = display_width / x and sY = display_hight / f(x).
I hope this gets you started somehow.
Here is some code to illustrate which way to go:
var x = 10
function setup() {
createCanvas(400, 400);
noLoop();
}
function my_func(x) {
return exp(x * 0.2);
}
function draw() {
background(220);
stroke(155);
strokeWeight(8);
noFill();
beginShape();
let nPoints = 20;
let dx = x / nPoints;
let ymax = my_func(x);
let dy = ymax / nPoints;
for (let i = 0; i <= x; i += dx) {
xValue = map(i, 0, x, 0, width);
yValue = map(my_func(i), 0, ymax, height, 0);
vertex(xValue, yValue);
}
endShape();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.1/p5.js"></script>
I omitted the ticks on the axes. I decided to create a static plot for the value of x in the between 0 and 10. The code can easily be changed into an animation by removing the noLoop(); statement in the setup function and adding the line x += somedelta; within the draw function.

Calculating the length of a cord and a bizarre result

I'm trying to calculate the length of a cord within the confines of a circle/ellipse in p5.js.
The parameters given are values and size. values is a simple array of 3 values: Hue, Saturation, and Brightness. The more important parameter is size which is the width and height of the shape (circle).
As the for loop iterates through the length of size the math is performed to derive half the cord length via Pythagorean theorem. r is half the size of size, or the radius. y is the current value of the for loop. r^2 - |y-r|^2 = x^2 where x is half the cord length (the absolute value is not required but it's more or less just for ensuring and debugging).
However, whenever I square r in the equation I receive the odd shape below. When I don't square r within the equation, I get the rotated square. The circle in the background is meant to represent the current HSL I am trying to display.
This happens when I don't square r
This happens when I square r
This is my current code:
this.draw = function(values, size) {
//angleMode(DEGREES);
this.gap = values[2];
this.r = size / 2;
this.lCol = map(values[1], 0, 100, 10, 70)
strokeUniform(this.lCol);
fillUniform(map(values[2], 0, 100, this.lCol + 20, 240));
strokeWeight(map(values[0], 0, 360, 0, 10));
translate(this.r, this.r, 0);
for (y = 0; y < size; y++) {
if (y % Math.floor(this.gap / 2) == 0) {
if (this.r > y) {
this.len = ((this.r ^ 2 - (Math.abs(this.r - y) ^ 2))) ^ 0.5;
line(0 - this.len, 0 - (this.r - y), 0 + this.len, 0 - (this.r - y));
} else {
this.len = ((this.r ^ 2 - ((y - this.r) ^ 2))) ^ 0.5;
line(0 - this.len, y - this.r, 0 + this.len, y - this.r);
}
}
}
}
This isn't doing what you expected it to:
r^2
The ^ symbol is the bitwise XOR operator and it works on binary numbers. For example:
var x = 5; // 0101
var y = 1; // 0001
var z = x ^ y; // 0100
console.log(z); // 4
In other words, the XOR operator looks at each digit in the binary representation of your number and the resulting digit is a 1 if only one of the arguments is a 1.
More info here:
JavaScript operators
Bitwise XOR
You probably want the Math.pow() function. More info can be found here.
Better yet, P5.js provides a sq() function. More info can be found in the P5.js reference.
Similarly, look for a Math.sqrt() or the P5.js sqrt() function instead of using ^ 0.5.

Acceleration regardless of device orientation

This javascript code measures the horizontal acceleration on the x axis. The intention is to measure the acceleration if the device was to move on a straight line parallel to the earth "horizontal" surface, irrespective of the device orientation.
Can that be done via gyroscope data during a given period of acceleration approx. 5 seconds? How? thx
let xAxis = '';
function handleMotionEvent(event) {
let x = event.accelerationIncludingGravity.x;
if (!xAxis) {
xAxis = x;
} else {
if (Math.abs(x - xAxis) > 0.4) {
console.log(x);
}
}
}
if (window.DeviceMotionEvent) {
window.addEventListener("devicemotion", handleMotionEvent, true);
}
Based on this documentation, the accelerationIncludingGravity property is an object providing information about acceleration on three axis. Each axis is represented with its own property:
x: acceleration in x axis (west to east)
y: acceleration in y axis (south to north)
z: acceleration in z axis (down to up)
So from mathematics, to get total horizontal acceleration we can combine x and y components using r^2 = x^2 + y^2 formula.
...
a = Math.sqrt(x*x + y*y); //horizontal acceleration
...

Math: 3 rotating dials with 3 values that should always = 100%

I have three dials: D1, D2 and D3. Together their values should always be 100% and their default Values are 50%, 25% and 25% respectively.
When a user edits D2 or D3, D1 should act as the FIRST pot to pull from and Deposit to.
Here is the problem: what if the editable dials are increased past the point of D1 reserves? I need to find a way to have the the remaining pull from the dial not being edited at that moment.
I guess I am looking for a elegant solution as opposed to a hack. Any one got such a solution?
http://jsfiddle.net/cborgia/ByWCA/
What you are trying to do is solve an equation of three functions like:
X + Y + Z = K;
where:
X = x + a(dx)
Y = y + b(dy)
Z = z + c(dz)
K = 100
and
a, b and c are functions
x, y and z are the current values of the knobs and
dx, dy and dz are the changes in knob values
The functions are solved given values for K (always 100) and one of X, Y and Z where X, Y and Z are in the range 0 to 100 inclusive.
You don't say what should happen as X, Y and Z approach 0 or 100 - are they proportionally reduced, or is the excess or deficit applied to the other non–user adjusted knob?

draw line to y value at angle

I calculated a direction (you can call it a vector if you want, but it's really a slope...) and I want to get an x value from a function given a y value.
Basically, I am trying to draw a line from an x, y value to an x, y value and I have the direction.
Say, given a slope/direction of 1/4 (rise over run), a starting point of 200, and an ending y value of 250, how would I find x?
I know this is really basic highschool algebra, but for some reason I can't conceptualize it...
If the end points are A(x1,y1) and B(x2,y2), the slope is defined as:
m = ( y2 - y1 ) / ( x2 - x1 )
Since you do have the slope, you need to have at least three coordinates in order to be able to compute the remaining one.
From your question I assume you want to compute y2. Therefore, you need to have x1, y1, and x2.
Example:
m = 1/4
A(1,1)
B(9,y2)
---
y2 = ?
m = ( y2 - y1 ) / ( x2 - x1 )
y2 - y1 = m * ( x2 - x1 )
y2 = m * ( x2 - x1 ) + y1
y2 = 1/4 * ( 9 - 1 ) + 1
y2 = 3
Use Bresenham's line algorithm
And here are implementations in a multitude of languages (including javascript)
Bresenham's line algorithm:
void DrawLineLCD(int x1,int y1,int x2,int y2,int nState)
{
unsigned int nTmp;
unsigned int nAlt=0;
int x,y; // where is the current pixel.
int dx; // dx is the delta for x
int dy; // dy is the delta for y
int StepVal=0; // variable for figuring out when to increment the other
axis.
if (x1>x2 && y1>y2)
{
nTmp=x2;
x2=x1;
x1=nTmp;
nTmp=y2;
y2=y1;
y1=nTmp;
dx=x2-x1; // dx is the delta for x
dy=y2-y1; // dy is the delta for y
}else
{
dx=x2-x1; // dx is the delta for x
dy=y2-y1; // dy is the delta for y
if (dy<0)
{
dy=-dy;
nTmp=y2;
y2=y1;
y1=nTmp;
nAlt=1;
}else
if (dx<0)
{
dx=-dx;
nTmp=x2;
x2=x1;
x1=nTmp;
nAlt=1;
}
}
if (nAlt)
{
if(dx>=dy) // The slope is less than 45 degres
{
y=y2;
for(x=x1; x<=x2; x++)
{
// Call your function to draw a pixel here.
SetPixelLCD(x,y,nState);
StepVal+=dy;
if(StepVal>=dx) // Increment y if enough x steps
// have been taken.
{
y--;
StepVal-=dx; // Reset StepVal, but
// not to 0. This gives even slopes.
}
}
}
else // The slope is greater than 45 degrees, just like
// above, but with y instead of x.
{
x=x2;
for(y=y1; y<=y2; y++)
{
// Call your function to draw a pixel here.
SetPixelLCD(x,y,nState);
StepVal+=dx;
if(StepVal>=dy)
{
x--;
StepVal-=dy;
}
}
}
return;
}
if(dx>=dy) // The slope is less than 45 degres
{
y=y1;
for(x=x1; x<=x2; x++)
{
// Call your function to draw a pixel here.
SetPixelLCD(x,y,nState);
StepVal+=dy;
if(StepVal>=dx) // Increment y if enough x steps
// have been taken.
{
y++;
StepVal-=dx; // Reset StepVal, but
// not to 0. This gives even slopes.
}
}
}
else // The slope is greater than 45 degrees, just like
// above, but with y instead of x.
{
x=x1;
for(y=y1; y<=y2; y++)
{
// Call your function to draw a pixel here.
SetPixelLCD(x,y,nState);
StepVal+=dx;
if(StepVal>=dy)
{
x++;
StepVal-=dy;
}
}
}
return;
}
Given a point (x1,y1) and a slope m then any other point on the line is given by
y = y1 + m*(x-x1) // point is (x,y)

Categories