Javascript. How to convert 2.5/3 to say 3/2 - javascript

var oneX = eval(prompt ("What's the x variable of the first set of points"));
var oneY = eval(prompt ("What's the y variable of the first set of points"));
var twoX = eval(prompt ("What's the x variable of the second set of points"));
var twoY = eval(prompt ("What's the y variable of the second set of points"));
console.log(oneX);
console.log(oneY);
console.log(twoX);
console.log(twoY);
var yRes = twoY-oneY;
var xRes = twoX-oneX;
console.log(yRes);
console.log(xRes);
var slope = xRes/yRes;
console.log("The slope is " + yRes + "/" + xRes);
This is my code. This is what the output looks like:
0.9166666666666666
0.8
2.09375
0.5714285714285714
-0.22857142857142865
1.1770833333333335
The slope is -0.22857142857142865/1.1770833333333335
However, I don't want -.22/1.177 I want -33/7 (I don't know the exact answer) I've never posted on StackOverflow before, so if I did something stupid while typing, I apologize. I'm new to programming so don't be too harsh.

The easiest way would be rounding to a certain fraction, e.g:
Math.round( slope * 10 ) + "/10"

What you're talking about is simplifying a ratio. First you multiply each number by the least common multiple to get them both into whole numbers, then divide each number by the greatest common factor to reduce them.
A full explanation of the process with examples: https://www.tutorialspoint.com/ratios_and_unit_rates/simplifying_ratio_decimals.htm

Related

Is there a JavaScript function to link ranges (top range 0----100 bottom range 55%----24%) known top input, want bottom value output

The following image will help explain what I am trying to achieve...
The top line (A) is a given calculated JavaScript value, lets call this the input.
The bottom line (B) is the output, so whatever input to (A) is given (will always be within the range) if a line (like the green one shown) were to be drawn I need the value of the output.
I have tried to search for phrases like "linked range", "parallel linked values" and similar but I think half of my problem is not knowing what this kind of calulation is called.
Usually I would be able to show what I have tried but on this one I really dont have a clue where to start.
Any help greatly appreciated.
So get the percentage in A
percentage = A[value] / ( A[max] - A[min] )
Use that to figure out the value in second
result = B[max] - percentage * (B[max] - B[min])
so basic JavaScript
var aMin = 0;
var aMax = 500;
var bMin = 24;
var bMax = 55;
var aValue = 100;
var percentage = aValue / ( aMax - aMin );
var result = bMax - percentage * (bMax - bMin);
console.log(result + "%");

Division by negative numbers

I am trying to calculate an angle in js using math js. I am experienced that when the division is between negative numbers js give me bad results. e.g. -6/-3 give me 20093 instead of 2.
How can I solve this? here below you can see a portion of console.log.
Here is the code:
var num = math.eval(parseInt(p[1]) - parseInt(d3.event.y));
var den = math.eval(parseInt(p[0]) - parseInt(d3.event.x));
if (den==0){
var angle = 0;
}else{
var m = math.eval(num/den);
if(m<1){
theta = m*100;
}else{
theta = m*100;
}
}
Syntax in code is num/den as you can see.
Thanks in advance
You can simply do -6/-3.
Run this in your developer tools console: alert(-6/-3); and you will see.
I think math.eval() expects a string like "-6/-3".

Converting Percent value to pixel in JavaScript or JQuery

I have a string value in percent unit that will be assign to height but before assigning I need to deduct another height which got by top() the output result is NaN, My code is as below:
var valHeight = "50%";
var result = valHeight - $("#item").css("top");
$("#AnotherItem").height(result);
as valHeight is string and percent and height is pixel the result will be NaN. How may I solve that issue? the valHeight is percent but top value is pixel. I need to have my result as percent
Let's clarify more:
I want to use calc function of CSS and I guess the below code is correct:
$('#AnotherItem').css('height', valHeight).css('height', '-='+itemOffsetTop);
the only problem is I want to use subtracted value in animate function.
First
valHeight is a string you need to convert that to number.
var varlHeight = parseInt("50px");
Second
Your $("#item").top() is invalid, use this instead.
$("#item").offset().top
Putting them together
var valHeight=parseInt("50px");
var result= valHeight - $("#item").offset().top;
$("#AnotherItem").height(result);
Update
Since you've updated your post with a '50%' value. How about doing this kind of approach instead.
var valHeight="50%";
var itemOffsetTop = $("#item").offset().top;
$('#AnotherItem').css('height', valHeight).css('height', '-='+itemOffsetTop);
I see two issues with your code:
valHeight is a string, not a number. It needs to be a number before using it in a math operation.
It's also not clear where you're getting .top() from. Perhaps you meant to use .offset().top?
Example:
var valHeight = 50;
var result = valHeight - $("#item").offset().top;
$("#AnotherItem").height(result + "px");
Now, you modified your question to use 50% and it doesn't really make sense. If you want the result to be 50% of $("#item").offset().top, then you could use something like this:
var valHeight = 0.5;
var result = $("#item").offset().top * valHeight;
$("#AnotherItem").height(result + "px");
You need to use .offset() as there is no method as .top() in jQuery
Get the current coordinates of the first element, or set the coordinates of every element, in the set of matched elements, relative to the document.
valHeight should be a number
Code
var valHeight = 50; //Or, parseInt("50px")
var result = valHeight - $("#item").offset().top;
$("#AnotherItem").height(result + "px");

getting NaN message in javascript while adding up multiple text fields

I am developing a simple application form where I am calculating experiences from maximum three employers. Now I want to add them up . The experiences are in the form of X years Y months and Z days. I have written following javascript function --
function total(){
var td;
var fd=parseInt(document.getElementById("LoS_days1").value);
var sd=parseInt(document.getElementById("LoS_days2").value);
var ld=parseInt(document.getElementById("LoS_days3").value);
var tm;
var fm=parseInt(document.getElementById("LoS_months1").value);
var sm=parseInt(document.getElementById("LoS_months2").value);
var lm=parseInt(document.getElementById("LoS_months3").value);
var ty;
var fy=parseInt(document.getElementById("LoS_year1").value);
var sy=parseInt(document.getElementById("LoS_year2").value);
var ly=parseInt(document.getElementById("LoS_year3").value);
td = (fd +sd +ld);
var rd = td%30;
var cm = Math.floor(td/30);
document.getElementById("Totalexp_day").value=rd;
tm = (cm + fm +sm +lm);
var rm = tm%12;
var cy = Math.floor(ty/12);
document.getElementById("Totalexp_month").value=rm;
ty = (cy + fy +sy +ly);
document.getElementById("Totalexp_year").value=ty;
}
I am getting a NaN message in each of the Totalexp_day, Totalexp_month and Totalexp_day field. Earlier I had some modified code that was not showing NaN message but it was not showing the desired results. Kindly suggest what to do to eliminate these two errors.
parseInt(document.getElementById("LoS_days1").value)
if the first character of the string cannot be converted to a number, parseInt will return NaN.
To avoid this, you can so something like is suggested here:
parseInt(document.getElementById("LoS_days1").value) || 0
If document.getElementById("Totalexp_day").value is empty then also it will return NaN. Make sure you have some number there.
Second alternative is reading document.getElementById("Totalexp_day").innerHTML and then applying parseInt
Probably you alert or console log the document.getElementById("Totalexp_day").value you would be more clearer why this problem is comming

Is Javascript multiplying these values wrong?

Allright, I know what machine precision is, but this, I can't understand...
Code:
console.log("meanX",meanX);
meanX2 = meanX * meanX; //squared
console.log("meanX2",meanX2);
Console output:
meanX 300.3
meanX2 28493.4400000000002
In case you are wondering, the correct value for meanX2 would be 90180.09
And this is only one of the many examples visible in the screenshot..
.toFixed(6) seems to fix this... But I have no idea why it doesn't work without it.
Edit
Ok, I don't want to post the whole program code here because in first place I'm not the only author, and second, I also wouldn't like this to be copied without our permission. But I'll gladly explain how I get this error and will post the whole method/function code here.
This code belongs, as you may have guessed from the window title, to a lane detection algorithm. We use Three.js/webgl to run some pre processing shaders on each frame of a video and then we analyze the resulting image. The method/function you see on the screenshot is a perpendicular line fitting algorithm and is part of the whole thing.
I can see the algorithm running nicely because I have the lane being drawn on top of the video, and It is well placed. Until suddenly the lane turns into an horizontal bar. This unexpected behavior happens exactly because of the phenomenon I described here, since it's from that moment that I start to see wrong math in the console.
Also, because the video and algorithm run at slightly different fps everytime, the problem doesn't always happen in the same moment of the video, and sometimes It doesn't happen at all.
Here is the code (it has some alterations because I was trying to isolate the issue):
this.perpendicularLineFit = function (points, slopeSign) {
var count = points.length;
var sumX = 0,
sumY = 0;
var sumX2 = 0,
sumY2 = 0,
sumXY = 0;
var meanX, meanY;
var i, lowp = {}, highp = {};
var B;
var slope;
var originY;
for (i = 0; i < count; i++) {
sumX += points[i].x;
sumY += points[i].y;
sumX2 += points[i].x * points[i].x;
sumY2 += points[i].y * points[i].y;
sumXY += points[i].y * points[i].x;
}
meanX = sumX / count;
meanY = sumY / count;
//If you uncoment this, problem reappears:
//var numeratorLeft = meanY * meanY;
console.log("meanX",meanX);
var meanX2 = meanX*meanX;
console.log("meanX2",meanX2);
var numerator = (sumY2 - count * (meanY * meanY)) - (sumX2 - count * meanX2);
var denominator = (count * meanX * meanY - sumXY);
B = 0.5 * (numerator / denominator);
slope = -B + slopeSign * Math.sqrt(B * B + 1);
originY = meanY - slope * meanX;
slope = isNaN(slope) ? slopeSign : slope;
originY = isNaN(originY) ? originY : originY;
lowp.y = this.lowY;
lowp.x = (this.lowY - originY) / slope;
highp.y = this.highY;
highp.x = (this.highY - originY) / slope;
return {
low: lowp,
high: highp
};
};
Now, I was trying to understand what was causing this, and the most bizarre thing is that it seems that when I place a statement of this form
var x = ... meanY * meanY ...;
before the meanX2 attribution, the issue happens. Otherwise it doesn't.
Also, I tried to catch this anomaly in the debugger but just when I enter the debugging tab, the problem disapears. And the values turn correct again.
I certainly don't believe in black magic, and I know that you are probably skeptic to this.
I would be too. But here is a link to a video showing it happening:
The video
Edit2:
I managed to reproduce this issue in another computer.. Both having ubuntu and using firefox (versions 20 and 21).
Edit3:
I'm sorry it took so much time! Here is a zip containing the issue. Just run it in any webserver. The code mentioned is in LaneDetection.js. Search for "HERE" in the file to find it.
https://docs.google.com/file/d/0B7y9wWiGlcYnYlo1S2pBelR1cHM/edit?usp=sharing
The problem might not happen in the first attempts. If that's the case refresh the page and try again. When the lines get horizontal you know it's there. As I said, I saw this problem happening in firefox versions 20 and 21 on ubuntu. In chrome it never happened.
By the way, I noticed that changing javascript.options.typeinference flag in firefox seems to stop the problem... I don't know exactly what that flag does, but maybe this optimization is not correctly implemented in firefox?
I can't say for sure that I actually have an answer but I think that I have confirmed that basilikum was correct to suggest a memory problem. Here's what I did: I took the first ten entries from your screenshot and calculated the correct answer. I then converted the correct answer and the wrong answer into the hexidecimal representation of the double-precision float. What I ended up with was the following:
292.416^2 = 85507.506 = 40F4E0381C71C71E
changed to 27583.373 = 40DAEFEB1C71C722
293.166^2 = 85946.694 = 40F4FBAB1C71C72A
changed to 27583.373 = 40DAEFEB1C71C722
295.818^2 = 87508.396 = 40F55D4658DC0876
changed to 28041.024 = 40DB62419637021F
294.500^2 = 86730.250 = 40F52CA400000000
changed to 27583.373 = 40DAEFEB1C71C722
297.000^2 = 88290.000 = 40F58E2000000000
changed to 28041.024 = 40DB62419637021F
221.750^2 = 49173.062 = 40E802A200000000
changed to 24964.000 = 40D8610000000000
300.300^2 = 90180.090 = 40F6044170A3D70A
changed to 28493.440 = 40DBD35C28F5C290
220.200^2 = 48488.040 = 40E7AD0147AE147B
changed to 25408.360 = 40D8D0170A3D70A4
300.600^2 = 90360.360 = 40F60F85C28F5C29
changed to 28493.440 = 40DBD35C28F5C290
213.000^2 = 45369.000 = 40E6272000000000
changed to 28032.326 = 40DB6014E5E0A72E
There's no persistent pattern to the change but there are a couple instances that are very telling of a memory issue. In the first two entries you can see that bytes 1, 2 and 3 were unchanged. In the 9th entry there's something even more odd. It would appear that bytes 0 - 3 were shifted left by exactly 4 bits! Upon considering the statement that the problem doesn't arise until after some time has passed and in light of these two anomalies, I'm fairly confident that you're encountering some sort of memory issue. Could it be, dare I say, a stack overflow?

Categories