I have a data set needs to calculate the accuracy of it using KNN classifier, I have tried to do that using the below code but it does not work.could someone state why?
Actually I need to calculate the Acc from weka inside java
private void Fitness(){
double Acc = 0.0;
double tp=0;
double tn=0;
double fp=0;
double fn=0;
Acc = (tp + tn)/ (tp + tn + fp + fn);
}
In machine learning , calculating the accuracy is ,
number of correct predictions / total number of predictions
And the error margin is given by ,
number of wrong predictions / total number of predictions
Suppose ,I have made 10 total predictions out of which 2 were correct whereas 8 were incorrect.
Then Acc = 2 / 10 , error = 8 / 10
Related
I'm trying to write a program which uses a form of simulated annealing, though that's not too important
basically I have the following variables:
double temperature = 100000;
double coolingrate = 0.99;
double delta = 0.001;
I want to work out how to, using Math.log(), calculate the number of times i'll need to run temperature = temperature * coolingrate - without actually doing it - until temperature <= delta
Well, since you're trying to find the smallest n for which:
You can then derive:
Converted to natural logarithms (used by Math.log()):
Which would yield the following code (rounding up because your number of iterations has to be an integer number):
double n = Math.ceil(Math.log(delta / temperature) / Math.log(coolingrate))
For your specified values, that would yield a result of 1833.
I am doing a TVM project and not quite understand how the compound interest translates into code. I am using BA II Plus financial calculator as a reference.
Example: Find the future value of $100 payments made at the beginning of every month for 10 years if interest is 5% compounded quarterly.
In the financial calculator:
N: 120 (10y x 12m)
I/Y: 5% (annually interest rate)
P/Y: 12 (12 times per year)
C/Y: 4 (4 times per year)
PV: 0
PMT: 100
BGN: TRUE
FV: [CPT] [FV] => -15575.41334
Here is the future value method.
static public double fv(double r, int n, double pmt, double pv, int bgn) {
return -(pv * Math.pow(1 + r, n) + pmt * (1 + r * bgn) * (Math.pow(1 + r, n) - 1) / r);
}
Call the method using numbers from the example
// rate n pmt pv bgn
double fv = fv(0.05/12, 120, 100, 0, 1); // -15592.928894335751 which is wrong
It seems you are getting numerical errors in the computation.
Floating-point computations are inherently subject to rounding errors, and these can add up and become very large.
E.g. general background (long read):
https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html
You can try using a high-precision computation library.
E.g. some good options are mentioned in this answer:
https://stackoverflow.com/a/284588/9549171
edit: you could try to analyse the expression you are using with https://herbie.uwplse.org/ (but the web version times out on your expression, you'll have to download their software)
I need to calculate speed after each 10 seconds or less (currently i am using fused location api to get the location after each 10 seconds). The problem is that the equipment is too slow and sometimes it gives the distance covers equal to zero.
I have tried using Location.distanceBetween() but it also produces zeros even when the equipment is moving. I have tried to calculate distance by a formula but sometimes distance is too small that it gives zero.
Now i want to calculate average speed. I want to save the points obtained in 1 minute (6 lat long values). And then after each 10 seconds, i want to calculate average speed between them. Thus after each 10 seconds I will add one points at the end and remove one point from the start. That will remove the possibility of zero.
Now is there any formula that can calculate speed or distance from set of lat long values or any better approach will be highly appreciated.
You can calculate distance between two point, that are close enough, using simple geometry
deltaLngMeters = R * cos(latitude) * deltaLongitudeRadians;
deltaLatMeters = R * deltaLatitudeRadians;
whereas deltas are in radians, deltaLatitudeRadians = deltaLatitudeDegrees * pi / 180
Hence distance = sqrt(deltaLngMeters ^2 + deltaLatMeters ^ 2).
To sum up
function distance(point1, point2) {
var degToRad = Math.PI / 180;
return R * degToRad * Math.sqrt(Math.pow(Math.cos(point1.lat * degToRad ) * (point1.lng - point2.lng) , 2) + Math.pow(point1.lat - point2.lat, 2));
}
If you have array of six points, you can calculate average speed.
points = [{lat: .., lng: ..}, ... ]; // 6 points
distancesSum = 0;
for(i = 0; i < distances.length - 1; i++) {
distancesSum += distance(points[i], points[i + 1]);
}
return (distancesSum / (points.length - 1));
Yes, R is for the Earth radius, R = 6371000;// meters
You can use multi threading(Thread.sleep()) to calculate a formula repeatedly for every 10 seconds. You can verify it here https://beginnersbook.com/2013/03/multithreading-in-java/.
For small distances(hope the device won't move at speeds above 1 km/s), earth's surface can be treated as a plane. Then the latitude and longitude will be the coordinates of the device on the Cartesian plane attached to earth. Hence you can calculate the distance by this formula:
√(delta(longitude)^2 + delta(latitude)^2)
delta: difference
In my class, i have to calculate prices of 18 different building which have different prices and income. They also have changes in price when the money of quantity of the building increases.
For example: The building starts at 40 dollars when the quantity is 0. The price increments by 4 for each quantity. So if you own 1, the price to buy the next same building will be 44 in state of 40. So this is the method that will calculate the price just fine.
public float getBuildingPrice(float quantity)
{
float buildingNum = quantity;
float startingPrice = 40;
float costIncrease = 4;
float finalPrice;
finalPrice = startingPrice + (costIncrease*buildingNum);
return finalPrice;
}
The method above returns the price and i divided the calculated price with the income that comes to the building like this. 10 is the income
float storageWorth = buildingPrice/10;
The thing i am unable to do is to find out the amount of different building the user can buy in the most efficient way ( meaning highest income but lowest spending ) So it should be the lowest Price / income that should be fulfilling the condition but also keeping in mind that it must be in the budget that the user keys in. There is always a change in the price and i do not know how to compare multiple values ( 18 values ) with the extra condition to keep in the budget.
For example
Farm
Income - 1
5 buildings
Increment of 4
Price 40 + (5 * 4) = 60
Price over income = 60
Pen
Income - 5
4 Buildings
Increment of 20
Price 200 + (4 * 20) = 280
Price over income 280/5 = 56
So meaning to say the next building the user should buy is a pen because it has lower price/income. There is also chances that the price over income of both building is the same like if the building reaches 5 for pen building, both price over income of pen and farm will be 60.
This is a formulation of your problem that ends up a mixed integer and non linear programming problem:
For all building type i let's define:
Pi : price of building type i
Ci : Price increment of building type i
Mi : income for building type i
B : Budget
Ni : Number of buildings of type i purchased.
Purchasing Ni building of type i equals:
Sum for j=1 to Ni Pi + (j - 1) × Ci = Ni (Pi + ( Ni - 1) / 2 × Ci)
Mixed integer non linear programming formulation:
Maximise Sum for i Ni × Mi
Subject to : sum for i Ni (Pi + (Ni - 1) / 2 ×Ci) <= B
Note that Pi, Ci, Mi and B are constants. Decision variables are Ni
An other solution is to purchase a building at a time selecting the one with the maximum income per invested money as per the following ratio:
Mi / (Ni (Pi + ( Ni - 1) / 2 × Ci))
At each step you calculate the building with the maximum ratio, purchase a building, deduct the price of the budget and repeat until the budget is exhausted. I do not have a proof that you will get an optimum my following this algorithm.
Third solution pseudocode (brute force):
(income, index_list) function maximize_income(i, b)
if i > last_building_type
return 0, []
endif
max_income = 0
max_income_index = 0
while b >= P(i) - (j-1) * C(i)
b = b - P(i) - (j-1) * C(i)
(income, index_list) = maximize_income(i+1, b)
income = income + j * M(i)
if income > maximum_income
maximum_income = income
maximum_income_index = j
endif
endwhile
add maximum_income_index to index_list
return maximum_income, index_list
end function
index_list is an array containing the number of each type of building
Your problem is a linear programming problem. Such problems don't have easy answers.
To solve such problems, people have invented many smart algorithms like the Simplex Algorithm.
These alogrigthms work on a represenation of the problem that basically is a set of mathematical linear equations. You have to think hard about your problem and formulate these equations.
A C library to solve a LP problem forumlated this way is the GLPK (GNU Linear Programming Kit). There are frontends for Python and for Java.
Your question is not a programming problem. It is a mathematical problem that can be solved in any language. Give enough time, it can even be solved on paper.
Consider that a tax of 10% is applicable on all items except food. Also, an additional tax of of 5 % is applicable on imported items.
If the cost of a music CD is 12.49. The tax for the item will be 1.499.
If the cost of an imported bottle of perfume is 47.50, The tax on the item will be 7.125
There is a policy in place which says that taxes on an item should be rounded off to the nearest 0.05. Therefore, 1.499 should be rounded off to 1.5 and 7.125 should be rounded of to 7.25.
The above rounding requirment can be achieved using the logic :
(float) Math.ceil(taxAmount / 0.05f) * 0.05f;
Adding the tax to the cost of the item gives :
music CD : 12.49 + 1.5 = 13.99
imported box of chocolates : 47.50 + 7.25 = 54.65.
I am facing a problem for the following input :
If the cost of an imported box of chocolates is 11.85, the tax will be 0.5925
Using the rounding policy, the tax after rounding will be 0.6.
When we add 11.85 + 0.6 which are both floats, we get the result as 12.450001. Unlike the other inputs, this specific input gives a lot of decimal places as opposed to the 2 decimal places in the other outputs.
I tried using BigDecimal instead of float to store all the values with a scale set to 2 decimal places. The problem with this approach is that bigDecimal will throw an exception for some cases if a rounding policy is not specified. Providing a rounding policy for BigDecimal causes the total of the cost of the item and the applicable tax to be rounded of using the rounding policy provided to BigDecimal, thus altering the required output.
You can use long instead of double to use double you can do
double d = Math.round(d * 20) / 20.0; // round up to multiple of 0.05
to use long (as cents)
long l = (l + 3) / 5 * 5;
Although its often considered best practice to use int, long or BigDecimal most investment banks and funds use double because once you understand how to use them safely, they are simpler (than long) and faster (than BigDecimal) to use.
Store monetary amounts as integers (e.g. a number of cents).
This is a common issue - google will give you plenty of great explanations.
Here is one: Why not use Double or Float to represent currency?
This seems to be part of a famous tech interview problem
The point is to understand that you have to calculate the taxes and round that amount to the upper 0.05
to calculate the rounding i used this groovy script
import java.math.*
def myRound(BigDecimal d){
def scale = new BigDecimal("0.05")
def y = d.divide(scale)
println "y :$y"
// def q = y.round(new MathContext(0,RoundingMode.UP))
def q = y.setScale(0,BigDecimal.ROUND_UP)
println "q :$q (intero)"
def z = q.multiply(scale)
println "z :$z"
return z
}
def taxBy(BigDecimal d,BigDecimal t){
return myRound(d.multiply(t))
}
def importTax(BigDecimal d){
return taxBy(d,new BigDecimal("0.15"))
}
def importBaseTax(BigDecimal b){
return taxBy(d,new BigDecimal("0.05"))
}
ip = new BigDecimal("27.99")
ipt = importTax(ip)
println "${ip}-->${ipt} = ${ip+ipt}"
I hope this to be useful!
public static Float roundOffToNearest05(float value) {
float counter = value /0.05f;
long counterRounded = Math.round(counter);
float result = counterRounded * 0.05f;
DecimalFormat decimalFormat2 = new DecimalFormat("####0.00");
return Float.parseFloat(decimalFormat2.format(result));
}