• 0

Javascript math with negative values


Question

I am wondering if anyone has a method to deal with negative numbers in math equations for javascript. At the moment I will sometimes get negative numbers resulting from some math done, for example I take the maximum number value in a set of information, multiply it half and add that value back:


var maxLength = 100;
var minLength = 1;
var LengthBuffer = maxLength * .5;
var endLengthRange = maxLength + LengthBuffer ;
var startLengthRange = minLengthBuffer - LengthBuffer;


// The above should yield 150 and -49, the issue is in the next part.
// Due to needing to find a median between the end of this range and
// the start (which here should be 199/2) the following math does not work correctly

var lengthRange = endLengthRange - startLengthRange;


//this will return 101 and not 199.
[/CODE]

4 answers to this question

Recommended Posts

  • 0

I've been testing this in Chrome but I get the same answer in FF as well. I'll post the code up that I'm working with.


function randomFromTo(from, to){
return Math.round(Math.random() * (to - from + 1) + from);
}
randomFromTo(10,20); //18
randomFromTo(10,20); //10
randomFromTo(10,20); //15
randomFromTo(10,20); //20
var carPrices = new Array();
var carMiles = new Array();
var allCars = new Array();
for (i=0;i<400;i++) {
allCars[i] = new Array();
allCars[i][0] = "car "+(i+1);
allCars[i][1] = randomFromTo(1000,500000); //miles
allCars[i][2] = randomFromTo(5000,50000); //dollars
//document.write(allCars[i][0]+' Miles: '+allCars[i][1]+' Price $'+allCars[i][2]+'<br />')
}





totalMile = 0;
totalPrice = 0;
for(var i = 0; i < allCars.length - 1; ++i){
//document.write(totalMile+" + "+allCars[i][1]+" =");
totalMile = totalMile + allCars[i][1];
totalPrice = totalPrice + allCars[i][2];

carMiles [i] = allCars[i][1];
carPrices [i] = allCars[i][2];

//document.write(totalMile+'<br
}
//document.write(totalMile);
var totalCars = allCars.length;

var largestPrice = Math.max.apply(Math, carPrices);
var largestMiles = Math.max.apply(Math, carMiles);
var smallestPrice = Math.min.apply(Math, carPrices);
var smallestMiles = Math.min.apply(Math, carMiles);

var yourCar = new Array();
yourCar[0] = new Array();
yourCar[0][0] = 'car1';
yourCar[0][1] = 20000;
yourCar[0][2] = 25000;



var bufferMiles = largestMiles*.5;
var bufferPrice = largestPrice*.5;
// document.write('Your is '+yourCar[0][0]+' with '+yourCar[0][1]+' miles and is priced at $'+yourCar[0][2]+'<br />');
var yourCarMiles = yourCar[0][1];
var yourCarPrice = yourCar[0][2];
var startPriceRange = smallestPrice-bufferPrice;
var startMileRange = smallestMiles-bufferMiles;
var averageMile = totalMile/totalCars;
var averagePrice = totalPrice/totalCars;
var mileRangeEnd = largestMiles+bufferMiles;
var priceRangeEnd = largestPrice+bufferPrice;
var mileRange = mileRangeEnd - startMileRange; // Does not yield correct value
var priceRange = priceRangeEnd - startPriceRange; // Does not yield correct value
var mileMedian = mileRange*.5;
var priceMedian = priceRangeEnd*.5;
//document.write('Averagece: $' + averagePrice +'<br />');
//document.write('Averageeage: ' + averageMile +'<br />');
//document.write('numbercars: '+totalCars+'<br />');
//document.write('Highesteage: '+largestMiles+'<br />');
//document.write('Highestce: '+largestPrice+'<br />');
//document.write('Lowestce: '+smallestPrice+'<br />');
//document.write('Lowesteage: '+smallestMiles+'<br />');
document.write(mileRangeEnd+' - '+startMileRange+' = '+mileMedian+'<br />');
document.write('Middlee Range: '+priceMedian+'<br />');
document.write('Middlece Range: '+priceMedian+'<br />');
document.write('Middlee Range: '+mileMedian+'<br />');
[/CODE]

  • 0

Well, I'm stumped. From both your example code and your actual code, I'm always getting the values you're expecting. For example, startPriceRange gets set to -19590. priceRangeEnd gets set to 74442. priceRange gets (properly) set to 94032.

Tested in Safari, Chrome, and Firefox.

Edit: Is this the part that's confusing you?:

document.write(mileRangeEnd+' - '+startMileRange+' = '+mileMedian+'<br />');[/CODE]

If I'm understanding this correctly, you should be outputting mileRange in that example, not mileMedian.

This topic is now closed to further replies.
  • Posts

    • That’s why I love classic Notepad from W10 IOT LTSC. It opens up instantly, uses very little resources, is just a plain notepad and nothing more. the title should be notepad has lost focus.
    • Seeing my profile picture in Notepad creeped me out. I do not appreciate that Copilot is opt-out rather than opt-in. I don't want Notepad to have connectivity. The other improvements are fine, including the upcoming Markdown support (although I hate Markdown's handling of newlines with a passion).
    • More like Trelane: https://memory-alpha.fandom.com/wiki/Trelane But, yes, Q.  
    • This would come in handy to me as an Uber driver. My biggest pet peeve is when passengers listen to their own audio on their phones without using headphones when they can hear I'm already playing music through my car's head unit.
    • Astonishing new tech could kill headphones forever as it bends sound right into ears by Sayan Sen Imagine being able to listen to your favorite song or podcast out loud without disturbing anyone nearby even without wearing headphones. That’s what a team at Penn State University has been working on. Led by acoustics professor Yun Jing, they’ve come up with a clever way to create invisible audio zones called “audible enclaves” where sound can be heard only at one exact spot. They use ultrasound, which is normally inaudible to people, along with something called acoustic metasurfaces—tiny lenses that can bend sound in specific directions. By combining two ultrasound beams that travel in curved paths and meet at a single point, they’re able to make sound audible only at that intersection. As Jing explained, “The person standing at that point can hear sound, while anyone standing nearby would not. This creates a privacy barrier between people for private listening.” To make this happen, the system includes two ultrasonic speakers and the metasurface lenses, which were 3D printed by Xiaoxing Xia from Lawrence Livermore National Lab. Each beam has a slightly different frequency, and when they meet, a local reaction makes the sound audible. Neither beam is loud on its own—the sound only forms at that shared point. Jia-Xin “Jay” Zhong, one of the researchers, shared how they tested the idea: “We used a simulated head and torso dummy with microphones inside its ears to mimic what a human being hears at points along the ultrasonic beam trajectory, as well as a third microphone to scan the area of intersection. We confirmed that sound was not audible except at the point of intersection, which creates what we call an enclave.” One of the biggest advantages of their approach is that it works across a wide range of sound frequencies—between 125 Hz and 4 kHz, which covers most of what people can hears. Even in rooms where sound usually bounces around, their system held up well. And it’s surprisingly compact too: the whole setup measures about 16 centimeters, roughly the size of a pencil case. “We essentially created a virtual headset,” Zhong said. In practice, it means that someone standing in the audible enclave can hear what’s being played clearly, while everyone else around hears nothing at all. That could be especially useful in shared spaces like cars, classrooms, or open offices. Right now, the sound can travel about one meter and hits around 60 decibels which is similar to regular talking volume. The team believes they can push those limits further by using stronger ultrasound. All this might seem futuristic, but it’s grounded in solving a basic problem: how to direct sound only where it’s needed. If you’re into tech and sound design, this could open up a whole new world of personalized audio experiences. Source: Penn State, PNAS | Image via Depositphotos This article was generated with some help from AI and reviewed by an editor. Under Section 107 of the Copyright Act 1976, this material is used for the purpose of news reporting. Fair use is a use permitted by copyright statute that might otherwise be infringing.
  • Recent Achievements

    • First Post
      leoniDAM earned a badge
      First Post
    • Reacting Well
      Ian_ earned a badge
      Reacting Well
    • One Month Later
      Ian_ earned a badge
      One Month Later
    • Dedicated
      MacDaddyAz earned a badge
      Dedicated
    • Explorer
      cekicen went up a rank
      Explorer
  • Popular Contributors

    1. 1
      +primortal
      503
    2. 2
      ATLien_0
      211
    3. 3
      Michael Scrip
      197
    4. 4
      Xenon
      149
    5. 5
      +FloatingFatMan
      125
  • Tell a friend

    Love Neowin? Tell a friend!