JavaScript Math Expression Yields Different Results - javascript

The following is a line I have in my Javascript code. It outputs -5108024 and some change when sqftVal = 2828 and bathsVal = 3.5.
out.value = -6932000 + 221400 * Math.log(sqftVal) + 637.2*Math.exp(bathsVal) + 51640;
However, when I manually type this in my calculator, I get roughly -5099721 and some change. I get the same result in R. Why does JavaScript mess up the math, and what can I do to fix this?
Calculator/R input:
-6932000 + 221400 * ln(2828) + 637.2 * e^(3.5) + 51640 = -5099721.073
I don't believe this is a floating point error because as I add more terms, the difference becomes fairly large.
Plus, everything was matching up until I added the fourth term (+51640) which made no sense to me.

There must be some other code that is interfering with your values or something, because the code shown does not produce the value you report.
var sqftVal = 2828;
var bathsVal = 3.5;
var value = -6932000 + 221400 * Math.log(sqftVal) + 637.2*Math.exp(bathsVal) + 51640;
console.log(value);

Related

Isolating a part of a string

well... for begining, i m building some dumb and easy projects because i'm starting learning the world of front end development. One of those you can find in internet was this Color picker idea. Some page where with a button you can generate a random color. all random, no connections between the colors o something else.
(i'm not a native english speaker so sorry if i write something and you dont get it right)
Here's the link to the repository
so...
I build a function that makes a random HSL color randomizing the values and then building a string and puting that in the css
function getRandomHsl(){
let hueValue = 0;
hueValue = Math.floor(
Math.random() * (360 + 1)
)
let satValue = 0;
satValue = Math.floor(
Math.random() * (100 + 1)
)
let lightValue = 0;
lightValue = Math.floor(
Math.random() * (100 + 1)
)
return 'hsl(' + hueValue + ', ' + satValue + '%, ' + lightValue + '%)';}
if you can give me your opinion on that function and tell me if you would have done it inanother way.
so... i wanted to find the way to if the Lightness would have a low value the color of the font change it to some white or something like that. And this is what i figured out. (the first part of the code is the button changing the value of the background color of the main div. This works well. The problem comes after).
hslBtn.addEventListener('click', () => {
let hslStringComplete = getRandomHsl();
colorShowcase.textContent = hslStringComplete;
document.getElementById('color-container').style.backgroundColor = hslStringComplete;
/*================================= change the color font od the text when its to dark */
let hslLightValue = hslStringComplete;
let lightValue = hslLightValue.toString().substr(13,3).replace(/\D/g,'')
console.log(hslLightValue.substr(13,3).replace(/\D/g,''));
if(lightValue < 40){
innerHTML('input').style.color = "white";
}})
i have really strougle it out coming up with this idea so i want some opinion on how could i have done in other way.
PD: `if(lightValue < 40){
innerHTML('input').style.color = "white";}
this is hte HTML: <input class="background-container"><h3 class="forWhiteColor">Background Color : <span class="color-showcase">#messi</span></h3></input>
this part get me an error and the html doesn get changes. Here's the error.
console error
thanks in advance.
innerHTML('input') should probably be document.getElementById('color-container') instead.
also you should note that when you extract a part of a string, you get a string.
And comparing a string to a number won't work well, you first need to convert your string to a number with parseInt (for integers) or parseFloat (for float)

Return random json object by length of category

I have a json array with words in different languages that I want to alert randomly. The thing is that I have different number of words in every language, so when I use the code below, I am getting undefined at some cases (because some words has more languages than others, and so the length property is longer than it should be).
I have tried to use all.french.length at the end of line 2, but got an error. Does anybody know what should I do?
Thanks!
all = [{"english":"cat", "french":"chat"}, {"english":"dog"}]
let z = Math.floor(Math.random() * all.length);
alert('random: ' + all[z].french);
Edit: I want it only to alert words only in the language I defined in line 3. In this case, I want only to display french words: only alert "chat" again and again. My original data of words is larger than that, of course, and has more languages, so I can't use 0.
If you just want a random element where the translation french exists you can filter your array
const filteredArray = all.filter(element =>
element.french === "" || element.french);
let z = Math.floor(Math.random() * filteredArray.length);
alert('random: ' + filteredArray[z].french);
you can do that:
const all = [{"english":"cat", "french":"chat"}, {"english":"dog"}]
function myAlert(lang)
{
let arr = all.filter( e=>!!e[lang])
, z = Math.floor(Math.random() * arr.length)
;
alert('random: ' + arr[z][lang] )
}
myAlert('french')
myAlert('english')

How to write arguments in function?

I have been using functions but I am not able to tackle this.
What I have done is created a function, then made this to use the values provided by the document class or ids and do the work. Once work is done then just give the data back! It worked!
Now I want to make this function happen for two divs, the first function works good. The issue is with the second one. The function is correct, their is some other bug while writing the result.
Here is my code:
function time_untilCom(id) {
var Time2 = Date.parse(document.getElementById("time_" + 2).value);
var curTime2 = new Date();
var timeToWrite2 = "";
var seconds2 = Math.floor((curTime2 - Time2) / (1000));
if (seconds2 > 0 && seconds2 < 60) {// seconds..
timeToWrite2 = seconds2 + " seconds ago";
$('#update_' + 2).html(seconds2);
$('#jstime_' + 2).html(timeToWrite2 + " <b>Time that was captured!</b>");
}
}
If I use it as it is, it works! The issue comes when I try to replace these
("time_" + 2), ("#update_" + 2), ("#jstime" + 2) with ("time_" + id), ("#update_" + id), ("#jstime_" + id).
What i want to happen is that the function would be provided with a common ID that is applied throughout the div and use that ID, to get the value of time, convert it to seconds, do other stuff and then provide me with the result in the corresponding element with the id that was in the argument.
function works great, it do provide me with the result. But the issue is with the id its not being sent I guess. Or if is being sent then not being applied. What might be the issue here? And don't mind the seconds i have that covered too.
I am really very sorry for short code:
Pardon me, I was about to write the code for the function too. But electricity ran out!
Here is the code: onload="time_untilCom('2'), this is the way I am executing this.
And once in the main code, it will be executed like this: onload="time_untilCom(#row.Id) because I am using ASP.NET Web Pages I will be using the server side code to write the ID from Database. And will then user the ID throughtout the div to update the time!
From what I understand, you probably want to replace the second line
var Time2 = Date.parse(document.getElementById("time_" + 2).value);
with
var Time2 = Date.parse(document.getElementById(id).value);
And at the end you can also use
$('#'+id).html(timeToWrite2 + " <b>Time that was captured!</b>");
You are passing "id" as an argument, but you never use it inside the function. My question is: In your example you are using 2 as appendix to id attributes. Is it the 2 (or other numbers respectively) that you want to have as the id parameter of the function?
Then you could just replace each + 2 in your code by + id
function time_untilCom(id) {
var Time2 = Date.parse(document.getElementById("time_" + id).value);
var curTime2 = new Date();
var timeToWrite2 = "";
var seconds2 = Math.floor((curTime2 - Time2) / (1000));
if (seconds2 > 0 && seconds2 < 60) {// seconds..
timeToWrite2 = seconds2 + " seconds ago";
$('#update_' + id).html(seconds2);
$('#jstime_' + id).html(timeToWrite2 + " <b>Time that was captured!</b>");
}
}
EDIT: Please tell us where and how exactly do you call time_untilCom? Did you pass the id there?

Addition not working in Javascript

I'm really new to Javascript and trying to create a form where I'm running into some trouble...
When I use + it does not add up to the value, instead it just puts it back to back. Ex: 5+10 (510)
Here's my code if you want to take a look at it. I'd appreciate any help since I can't figure this out on my own.
var service = document.getElementById("service");
var serviceprice = service.options[service.selectedIndex].id;
var tech = document.getElementById("tech");
var techprice = tech.options[tech.selectedIndex].id;
var hours = document.getElementById("hours").value;
// The error happens here
var total = techprice * hours + serviceprice;
I also have an html part which the script gets the data from.
That happens whenever you have a string rather than a number. The + operator performs concatenation for strings. Make sure you parse your strings to numbers using parseFloat or parseInt:
var service = document.getElementById("service");
var serviceprice = parseInt(service.options[service.selectedIndex].id, 10);
var tech = document.getElementById("tech");
var techprice = parseInt(tech.options[tech.selectedIndex].id, 10);
var hours = parseInt(document.getElementById("hours").value, 10);
Note that parseInt takes an argument to specify the base. You almost always want base 10.
Try changing this line:
var total = techprice * hours + serviceprice;
to
var total = techprice * hours + parseFloat(serviceprice);
I suspect 'servicePrice' is a string, and it will then try to concatenate the first value (let's say: 100) with the second value (which is, not a number, but a string, let's say 'test'), the result being '100test'.
Try to convert the string to int first with parseInt or to float with parseFloat
This is not especially elegant, but I find it simple, easy, and useful:
var total = -(-techprice * hours - serviceprice);
or even:
var total = techprice * hours -(-serviceprice);
They both eliminate the ambiguous + operator.

JavaScript - Reposition a DIV incrementally onClick

Very simple code, very simple problem. When a link is pressed, it moves a div either up or down. However, I cannot get it to move incrementally. I know this is a simple syntax error, but google isn't revealing the error of my ways. Anyone willing to enlighten me?
<a class="galsel" onclick="document.getElementById('innerscroll').style.bottom -='167px';">«</a>
<a class="galsel" onclick="document.getElementById('innerscroll').style.bottom +='167px';">»</a>
I already have it so that the div tiles itself vertically, so I'm not worried about it going "too high" or "too low"
Here's what it looks like right now: drainteractive.com/FBD/projects.php
You have to parse the value from the string containing px
// Increase by 167
document.getElementById('innerscroll').style.bottom = (parseInt(document.getElementById('innerscroll').style.bottom, 10) + 167) + ' px'
// Decrease by 167
document.getElementById('innerscroll').style.bottom = (parseInt(document.getElementById('innerscroll').style.bottom, 10) - 167) + ' px'
// Abstracted
function addToBottom(el, amount) {
// You probably add lower and upper bound check conditions
el.style.bottom = (parseInt(el.style.bottom) + amount) + ' px';
}
var el = document.getElementById('innerscroll');
addToBottom(el, 167);
addToBottom(el, -167);
Also be sure to make it work for cases where bottom wasn't set initially
var currentBottom = parseInt(document.getElementById('innerscroll').style.bottom) || 0;
+='167px' will concatinate it an it will become '167px167px167px167px167px'. Not sure what will result -='167px', but probably will result an error.
You need to rip the 'px' off the string, convert(?) it to an int, then subtract from that.
onclick="var mElem = document.getElementById('innerScroll'); mCur = parseInt(mElem.style.bottom.replace('px', 0)); mElem.style.bottom = (mCur-167)+'px'"
Naturally, this should all be put into a separate function, who is then called in the onclick, rather than the monstrosity above.
function moveUp()
{
var mElem = document.getElementById('innerScroll');
var mCur = parseInt(mElem.style.bottom.replace('px', 0));
mElem.style.bottom = (mCur-167)+'px';
}
...
<strike>onlick="moveUp()"</strike>
onclick="moveUp()"
My mind must have been somewhere else..

Categories

Resources