Rounded float is returned with all decimals - rounding

I have a rest endpoint that returns some simple statistics: total votes, average vote,...
function getRatings($data) {
global $wpdb;
$struttura_id = intval( $data['struttura_id'] );
$sql = " SELECT COUNT(M.meta_key) as num_votes, SUM(M.meta_value) as tot_votes
FROM .... ";
$stats = $wpdb->get_row($sql);
return array('struttura_id'=>$struttura_id,
'num_votes' => $stats->num_votes,
'tot_votes'=> $stats->tot_votes,
'average'=> round($stats->tot_votes/$stats->num_votes,1) );
}
For some reason the average value is not rounded when I receive it as a REST response form WP rest API.
Response is:
{
"struttura_id": 115,
"num_votes": "3",
"tot_votes": "10",
"average": 3.2999999999999998
}
As you can see the average value is pretty "strange". Too much decimals and wrong precision (a good value should be 3.33333333)
What's wrong?

Related

Actionscript 3 error 1176 : Comparison between a value with static type Function and a possibly unrelated type int

I want to make coding about the final score display. If someone has done 10 multiple choice questions and he clicks on the final score button, then his final score will appear along with the description. The score will be made in a range according to the category, namely 1-59 = Under Average, 60-79 = Average, and 80-100 = Above Average.
I've tried coding it but I found error 1176 on line 7 and 11.
Can you help me fix it?
finalscorebutton.addEventListener(MouseEvent.CLICK, finalscore);
function finalscore(event:MouseEvent):void
{
multiplechoicefinalscore.text = sumofscores;
var finalscore:String = finalscore.toString;
finalscore = multiplechoicefinalscore..text;
if(finalscore.toString < 60){
description.text =
"UNDER AVERAGE.";
}
else if(finalscore.toString >= 60 && finalscore.toString <=79){
description.text =
"AVERAGE.";
}
else{
description.text =
"ABOVE AVERAGE.";
}
}
There are multiple syntax and logic errors.
Something.toString is a reference to a method, you probably mean Something.toString() which calls the said method and returns a text representation of whatever Something is.
You don't need a text representation because you want to compare numbers, you need a numeric representation (which is either int, uint or Number).
There are 2 dots in multiplechoicefinalscore..text, what does it even mean?
There is function finalscore and then you define var finalscore, defining things with the same names is a bad idea in general.
You should keep your script formatted properly, otherwise reading it and understanding would be a pain.
So, I assume you have the user's result is in sumofscores. I'm not sure if the script below will actually work as is, but at least it is logically and syntactically correct:
finalscorebutton.addEventListener(MouseEvent.CLICK, onFinal);
function onFinal(e:MouseEvent):void
{
// Ok, let's keep this one, I think you are putting
// the score result into some kind of TextField.
multiplechoicefinalscore.text = sumofscores;
// Get a definitely numeric representation of the score.
var aScore:int = int(sumofscores);
// In terms of logic, putting the complicated condition case
// under the "else" statement will simplify the program.
if (aScore < 60)
{
description.text = "UNDER AVERAGE.";
}
else if (aScore > 79)
{
description.text = "ABOVE AVERAGE.";
}
else
{
description.text = "AVERAGE.";
}
}

Response architecture

I have the following question.
I have an endpoint which returns some data with the following format.
[
{
avr_video_likes = 15;
avr_video_likes_ratio = 3;
avr_video_views = 1500;
avr_views_ratio = 7.2;
avr_video_comments = 4;
avr_video_comments_ratio = 75;
}
.....
]
the possible values are 0 or positive ones.
So I was wondering, if a value doesnt exist at all in my database which is the the best response to send.
Return -1 in order to show that the value doesnt exist. Because values are type of number
Return "-"
Dont return the value at all.
Which one is the best option and why?
Thank you for your time

Get real-time distance between running cars on Azure Stream Analytics

We will get streaming data of many cars on a particular Stream Analytics. Each row will have vehicleId, latitude and longitude of vehicle. I need to raise an alarm whenever distance between ANY two cars is less than suppose x meters.
Right now we can consider radial distance to keep it simple. Hence, we need to calculate distance of cars NOT from a fix point but from other cars ( near by cars can keep changing with time ). Hence, we cannot hard-code vehicle id in the query for sure.
We do have Geo-spatial functions support https://learn.microsoft.com/en-us/stream-analytics-query/geospatial-functions ..
I am not sure if this can even be done by Stream Analytics query directly.
I created a small example of the potential solution, not perfect one perhaps, but it resolves the problem in the ASA job.
Essentially I have re-used javascript function that expects simple latitude and longitude and gives the distance in meters. You can use potentially the geospatial embedded function - I haven't tried to play with that.
So, idea is to cross join input, for all input messages(unfortunately yes, you get duplicated result but it works), and then you apply distance function and filter to the output only those that have a distance less than a threshold value. The following example propagates to the output only if the distance is not zero(it means it compared with itself) and if it is less than 5 meters:
with inputData as (select * from input i1 inner join input i2 ON DATEDIFF(second,i1,i2) BETWEEN 0 AND 5),
distances as (select *, udf.getGeoDistance(i1.lat,i1.long,i2.lat,i2.long) as distance from inputData)
select *
into output
from distances
where distance <> 0 and distance < 5
UDF function:
// Sample UDF which returns sum of two values.
function getDistanceFromLatLonInKm(lat1, lon1, lat2, lon2) {
'use strict';
var R = 6371; // Radius of the earth in km
var dLat = deg2rad(lat2 - lat1); // deg2rad below
var dLon = deg2rad(lon2 - lon1);
var a =
Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) *
Math.sin(dLon / 2) * Math.sin(dLon / 2)
;
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
var d = R * c * 1000; // Distance in m
return d;
}
function deg2rad(deg) {
return deg * (Math.PI / 180);
}
Input:
[
{
"name" : "car1",
"lat" : 59.3293371,
"long" : 13.4877472
},
{
"name" : "car2",
"lat" : 59.293371,
"long" : 13.2619422
},
{
"name" : "car3",
"lat" : 59.3293371,
"long" : 13.4877040
}
]
And result(car1 and car3 are close to each other):
Follow your latest comment,you use tumbling-window and set 5 seconds timeunit to get slice of data.Per my knowledge, you still could not calculate distance of cars each other by sql and Geo-spatial functions directly.Not to mention a warning.
I came up with an idea that you may could use Azure Function as the output of ASA job.Collect the slice of data and send them into Azure Function as json parameter.Inside function,you could write code to calculate the distances between cars each other,even alert warnings to other destinations.

Find 2nd most significant digit

I have a scenario where I need to compare two numbers and determine if there is a difference in the 2nd most significant digit. These numbers are decimal with 10 places.
0.0000098765
0.0000098766
// Change = false
0.0000098765
0.0000099765
// Change = true
0.0000098765
0.0000198765
// Change = true
Looking at my examples above and rethinking the question I would want to know when either the 2nd or 1st significant digits change.
I know how to round however I have no idea how to approach this problem.
function significantDigitChange(number1, number2) {
var shift1 = number1 * Math.pow(10,10);
var shift2 = number2 * Math.pow(10,10);
if ( shift1.toString().slice(0,2) != shift2.toString().slice(0,2) ) {
return true
} else {
return false
}
}
Make a function to truncate a (positive) number to some significant digits:
function toPrecision(n, precision) {
var scale = 10 ** (Math.floor(Math.log10(n)) - precision + 1);
return Math.trunc(n / scale) * scale;
}
Use it on both values and compare for equality:
function significantDigitChange(n1, n2) {
return toPrecision(n1, 2) !== toPrecision(n2, 2);
}

What is wrong with my code to calculate a standard deviation?

I'm trying to calculate the standard deviation of a set of numbers as Excel would with the STDEVPA() function, but I'm not getting the correct result. I'm following this formula:
Here is my [Node] code:
var _ = require('underscore');
var prices = [
1.37312,
1.35973,
1.35493,
1.34877,
1.34853,
1.35677,
1.36079,
1.36917,
1.36769,
1.3648,
1.37473,
1.37988,
1.37527,
1.38053,
1.37752,
1.38652,
1.39685,
1.39856,
1.39684,
1.39027
];
var standardDeviation = 0;
var average = _(prices).reduce(function(total, price) {
return total + price;
}) / prices.length;
var squaredDeviations = _(prices).reduce(function(total, price) {
var deviation = price - average;
var deviationSquared = deviation * deviation;
return total + deviationSquared;
});
var standardDeviation = Math.sqrt(squaredDeviations / prices.length);
console.log(standardDeviation);
When I run this, I get 0.26246286981807065, and instead I should get 0.0152.
Please note that I posted on StackOverflow and not the Mathematics site because, in my opinion, this is more geared toward programming than mathematics. If I post there, they will tell me to post here because this is related to programming.
If you console.log(total) inside your calculation of squaredDeviations, you'll see you're starting out with the value 1.37312, namely the first thing in your list. You need to explicitly tell it to start at 0, which is the third optional argument to reduce. Just replace:
var squaredDeviations = _(prices).reduce(function(total, price) {
var deviation = price - average;
var deviationSquared = deviation * deviation;
return total + deviationSquared;
});
with
var squaredDeviations = _(prices).reduce(function(total, price) {
var deviation = price - average;
var deviationSquared = deviation * deviation;
return total + deviationSquared;
}, 0);
See the underscore documentation for more details. In particular, note that things work when calculating the mean without passing this additional argument because, in said case, the iteratee function will not be applied to the first element.

Resources