Inverted proportion - javascript

I have information that
1X = 98 N
98X = 0.01020408163265306 N
How can I calculate number N based on number X from range 1 to 98, knowing that when number X=1 is equal N=98 and when X=98 then N=0.01020408163265306
Maybe it is silly, but how to write function to calculate number N from X ?

Update: Now that you've posted more data, I'll amend my answer to say that this function does a pretty good job of approximating the data you provided:
y = 100*exp(-x/3.5)
I guessed a form that uses the exponential function. The value at zero is clear, as is the value when x becomes large. I guessed a time constant that gave a good visual fit.

You can think of it as a fractional function;
Result = N/(X squared)
Hopefully this is what you were looking for. But if you want N to be a function of X:
N = 1/X, which is an inverse function.

Related

Find the 'step' value from an arbitrary array that is guaranteed to be in a certain 'step' amount

I've looked around and have not found any answers for this. The problem seems pretty simple at first.
Let's say we have an array like this. We can assume that the array will ALWAYS have some equal thing it counts up by (each element has the same difference between the elements adjacent to it).
[1.0,1.1,1.2,1.3,1.4,1.5,1.6,1.7,1.8,1.9,2.0]
The answer to above would be 0.1.
Another example might be an array like this.
[0.2,0.4,0.6,0.8,1.0,1.2,1.4]
This answer would be 0.2
One possible solution is I could read the first and second parameters of the array and capture the difference and that will be my 'step'. Is this the best way to go about doing this? Is there any downsides to this approach?
if the array was counting downward like this:
[0.8,0.6,0.4,0.2], then how could I extract the step successfully?
In this case I need the answer -0.2, my answer would not work, and taking the absolute value would give me 0.2 not -0.2.
This is the same as taking the common difference of an arithmetic progression in mathematics. You can just subtract a term from the previous term, and you'll get the difference. Here is how the array would look in general terms:
[a, a + d, a + 2d, a + 3d, ...]
So from this you can easily see that if you perform (a + d) - (a), you'll get d. Subtracting any element from the previous element will yield the same result. So the simplest way to do this would be:
const getStep = array => (array[1] - array[0]);
Demonstration using your three provided arrays:
const getStep = array => (array[1] - array[0]);
console.log(getStep([1.0,1.1,1.2,1.3,1.4,1.5,1.6,1.7,1.8,1.9,2.0]));
console.log(getStep([0.2,0.4,0.6,0.8,1.0,1.2,1.4]));
console.log(getStep([0.8,0.6,0.4,0.2]));
Note that the above values may be inaccurate as they're floating point numbers (Floating point math is broken) but you can just round it to the nearest x-th decimal place (here's a solution with a 1/10th rounding, for instance):
const getStep = array => Math.round((array[1] - array[0]) * 10) / 10;
console.log(getStep([1.0,1.1,1.2,1.3,1.4,1.5,1.6,1.7,1.8,1.9,2.0]));
console.log(getStep([0.2,0.4,0.6,0.8,1.0,1.2,1.4]));
console.log(getStep([0.8,0.6,0.4,0.2]));
You don't need any special-case logic for the case of counting downward. In your second example, you simply subtract the first term from the second, 0.6 - 0.8, and get the correct answer: -0.2. This is similar to how in your first example, you subtracted the first term from the second, 0.4 - 0.2 and got the correct answer.
To convince you that this works, consider that your array starts with a real number n, and increases by a real number k each step:
[n, n + k, n + k*2, n + k*3, ...]
Then you can subtract the first two terms:
(n + k) - n
to get
k
The sign of k doesn't matter.
This in math is called arithmetic progression.
If you guarantee that the sequence have the same step, you surely can just take the difference between the 2 first numbers of the sequence.
when you count downwards your sequence is decrescent, so, your step is negative.
There is no possible way to get this sequence downwards without a negative step
This function:
function arrayStep(arrayValue) {
let step = arrayValue[1] - arrayValue[0];
return step;
}
ps: if I understand correctly, the answer of the first example would be 0.1

How to calculate for the ln of a given number?

Good day all.
The google scientific calculator lets you calculate the ln of a given number.
examples:
ln(1) = 0
ln(2) = 0.69314718056
I've been trying to figure out the equation used by it to arrive at the answer. Any leads would be welcome.
I'm bad at math as you can tell. :(
If you want to verify the value for yourself, as some kind of programming exercise, the classical formula for the natural or Neperian (Napier's) logarithm is
ln(a)=limit(n -> inf) n*(root(n,a)-1),
so start with
n=1, a=2
and loop
n=n*2, a=sqrt(a),
output n*(a-1)
until some kind of convergence is reached. This will break down at some point due to the limits of floating point numbers, the repeated square root converges very fast towards 1.
The traditional definition without using the exponential function is via the integral
ln(a) = integral( 1/x, x=1..a)
where you can use the trapezoid or Simpson method of numerical integration to get increasingly more accurate results.
From the integral formula one gets via the geometric series the power series of the logarithm. A series based formula that will converge a little faster than the direct power series starts with the identity
ln(2)=ln(4/3)-ln(2/3)=ln(1+1/3)-ln(1-1/3)
from
a = (1+x)/(1-x) <==> x = (a-1)/(a+1).
Using
ln(1+x)=x-x^2/2+x^3/3-x^4/4+x^5/5-+...
the even powers in the above difference cancel, and
ln(1+x)-ln(1-x)=2*x*(1+x^2/3+x^4/5+...),
So for the computation of ln(2) initialize
x=1/3, xx=x*x, n=1, xpow=1, sum=0
and loop
sum+=xpow/n, xpow *= xx, n+=2
output 2*x*sum
again until some kind of convergence is reached.
ln x gives you the natural logarithm of x (or the value of y that makes the equation e^y = x true, where e is Euler's number)
Math.log(2);
The result will be:
0.6931471805599453
The log() method returns the natural logarithm (base E) of a number.
Note: If the parameter x is negative, NaN is returned.
Note: If the parameter x is 0, -Infinity is returned.

calculate a derivative in javascript

To calculated the value of the derivative of a given function Func at a given point x, to get a good precision one would think this:
a = Fun( x - Number.MIN_VALUE)
b = Func( x + Number.MIN_VALUE)
return (b-a)/(2*Number.MIN_VALUE)
Now for any x + Number.MIN_VALUE (or x - Number.MIN_VALUE) both return x in javascript.
I tried of different values, and 1 + 1e-15 returns 1.000000000000001. Trying to get more precision, 1 + 1e-16 returns 1. So I'll have to use 1e-15 instead of Number.MIN_VALUE which is 5e-324.
Is there a way to get a better precision in this case in javascript?
This is not at all about javascript, actually.
Reducing the separation between the points will not increase your precision of the derivative. The values of the function in the close points will be computed with some error in the last digits, and finally, your error will be much larger than the point separation. Then you divide very small difference which has a huge relative error by a very small number, and you most likely get complete rubbish.
The best way to get a better value of the derivative is to calculate function in multiple points (with not very small separation) and then construct an approximation polynomial and differentiate it in the point of your interest.

32.48 * 10 = 324.79999999999995 in javascript calculations

var quantity = $(this).find('td:eq(2) input').val()*1;
var unitprice = $(this).find('td:eq(3) input').val()*1;
var totaltax = 0;
$(this).find('td:eq(4) input[name^=taxamount]').each(function(){
totaltax = (totaltax*1)+($(this).val()*1);
});
var subtotal = (unitprice+totaltax);
alert(subtotal+' is unit subtotal, to mulitply by '+quantity);
var total = subtotal*quantity;
$(this).find('td:last').html('$'+total);
In this case, based on my DOM, the results are all integers (especially because I'm making sure I apply the *1 modifier to values to ensure they are numbers, not strings).
In this case, these are teh values returned within the first 7 lines of the above code (and verified through alert command)
quantity: 10
unitprice: 29
totaltax: 3.48
subtotal = 32.48
When I multiply subtotal*quantity for the total variable, total returns:
total: 324.79999999999995
So at the end, I get the td:last filled with $324.79999999999995 rather than $324.80 which would be more correct.
Bizarre, I know. I tried all sorts of alerts at different points to ensure there were no errors etc.
This has been asked one bizillion times.
Please read: What Every Computer Scientist Should Know About Floating-Point Arithmetic
You're coming up against a familiar issue with floating point values: certain values can't be precisely represented in a finite binary floating point number.
See here:
How to deal with floating point number precision in JavaScript?
This is the way floating point numbers work. There's nothing bizarre going on here.
I'd recommend that you round the value appropriately for display.
That's the joy of floating point arithmetic -- some base 10 decimals cannot be represented in binary.
http://en.wikipedia.org/wiki/Floating_point#Accuracy_problems
Computers can't handle decimals very well in binary since in real mathematics there are literally an infinite number of values between 0.01 and 0.02 for example. So they need to store approximations, and when you do arithmetic on those approximations the results can get a little away from the true result.
You can fix it with (Math.round(total*100)/100).toFixed(2);
As others have mentioned, this is the way its meant to work. A suggested workaround can be found below:
var v = "324.32999999999995";
function roundFloat(n, d) {
var a= Math.pow(10, d);
var b= Math.round(n * a) / a;
return b;
}
$("body").append(roundFloat(v,3));
Where v would be replaced with the desired value.
You can view the working example at: http://jsfiddle.net/QZXhc/
You could try rounding to 2 decimal digits as workaround

How to make 5509.099999999999 as 5509.09 using javascript

How to make 5509.099999999999 as 5509.09 using javascript.
Lots of mathy options that end up with .1 so how about;
var f = 5509.099999999999
if ((f = f.toString()).indexOf(".") >= 0)
f = f.substr(0, 3 + f.indexOf("."))
print(parseFloat(f))
>>5509.09
Have you tried this?
var value = 5509.099999999999;
var str = value.toString();
var result = str.substr(0,7);
Then if you need it to be a float again you can do:
var FinalAnswer = parseFloat(result);
You don't need all these variables, but that is the step by step.
var result = (Math.round((5509.09999 * 100) - 1)) / 100;
You could use .toFixed(2) but this will round the value, so in your example you'll end up with 5509.10 instead of 5509.09.
The next best option is to use Math.floor(), which truncates rather than rounding. Unfortunately, this only gives integer results, so to get the result to 2 decimal places, you'd need to multiply by 100, then use Math.floor(), and then divide by 100 again.
var value = 5509.099999999999;
var result = Math.floor(value*100)/100;
[EDIT]
Hmm, unfortunately, the above doesn't work due to problems with floating point precision -- even just the first step of multiplying it by 100 gives 550910.
Which means that the best answer is likely to be converting it to a string and chopping the string into bits.
var value = 5509.099999999999;
var str_value = value.toString();
var bits = str_value.split('.');
var result = bits[0]+"."+bits[1].substr(0,2);
I wouldn't normally suggest doing string manipulation for this sort of thing, because it is obviously a maths problem, but given the specific requirements of the question, it does seem that this is the only workable solution in this case.
You can truncate the number to a certain number of decimal places using this function:
function truncateNumber(number, digits){
var divisor = Math.pow(10,digits);
return Math.floor(number*divisor)/divisor;
}
If you want to round the number instead, you can use JavaScript's built in Number.toFixed function. If you always want the number a certain number of digits long, you can use the Number.toPrecision function.
if you want to take two decimal places, you can use .toPrecision(n) javascript function, where n is the total number of digits desired.
so, for your example, you'd have to do
var x = 5509.099999999999;
x = x.toPrecision(6);
this, however, rounds results in 5509.10

Categories

Resources