public class Prices {
public static void main(String[] args) {
int i = 100;
int z = 0;
int x = 0;
int a = 0;
int v = 0;
double sum = 0;
double[][] MovingAvgArray = new double[i][i];
double[] List = {20.19, 21.67, 22.49, 22.26,23.99, 23.75, 23.34, 23.54, 23.25, 23.9, 23.84, 23.19, 22.03, 22.7, 21.14, 22.54, 24.36, 24.85, 23.96, 25.1, 20.79, 19.96, 19.98, 19.54, 19.09, 18.47, 18.59, 18.96, 18.93, 18.79, 19.06, 19.82, 19.5, 19.13, 19.25, 18.9, 19.05, 19.02, 19.09, 18.73, 18.44, 18.65, 18.07, 18.12, 17.92, 18.21, 17.81, 18.57, 18.92, 18.4, 17.83, 17.83, 18.55, 18.25, 18.55, 17.72, 17.28, 17.37, 16.99, 16.28, 17.02, 15.68, 15.73, 16.45, 15.54, 15.15, 15.51, 15.51, 15.54, 15.05, 14.98, 15.88, 16.14, 16.2, 16, 16.82, 17.74, 18.01, 17.99, 18.01, 16.99, 18, 18.3, 19.02, 18.14, 18.95, 19.19, 18.67, 17.63, 17.6, 17.56, 18.59, 18.57, 19.07, 19.57, 19.59, 18.71, 18.71, 18.75, 19.37};
do{
do{
for(;v < a + x +2;)
{
sum = sum + List[v];
v++;
}
MovingAvgArray[x][z] = sum;
MovingAvgArray[x][z] = (MovingAvgArray[x][z])/(x + 2.0);
System.out.println(MovingAvgArray[x][z]);
z++;
a++;
sum = 0;
v--;
}while(z<100-(x+1));
v = 0;
z=0;
x++;
}while(x<i-2);
}
}
The goal of this program is to get the moving average(which is calculated in the for loop) of the List of data, starting at the moving average of the first two numbers, then the first three, ect. and plug it into MovingAvgArray. The moving average of two numbers would be on the array values [0][0 through (i-3)], the average of three numbers would be on values [0][0 through (i-4)], ect ect. Until this is no longer possible.
If i take out the outermost do-while loop the program runs without error, but only calculates the moving average for two numbers(there will be 98 of them).
When i try to loop it to do three numbers which is the above code i get the error "Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 100" on the line that says "sum=sum+List[v];
which im pretty sure means that the v in List[v] is a number that is greater than the values listed in List[v]. (its trying to get the 101th value in a array that only has 100 values).
The problem is i have no idea why this is happening because "v" should be set back to 0 before this loop tries to run again.
I have allowed myself to add extra println's to the code, like
v--;
System.out.println(" ------------------ v=" + v);
System.out.println(" ------------------ z=" + z);
System.out.println(" ------------------ x=" + x);
System.out.println(" ------------------ a=" + a);
} while (z < 100 - (x + 1));
System.out.println(" HERE ");
v = 0;
just to observe that:
19.060000000000002
------------------ v=99
------------------ z=99
------------------ x=0
------------------ a=99
HERE
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 100
at Prices.main(Prices.java:24)
this means that the loop controlled by
while (z < 100 - (x + 1))
ends. a is still 99, x is increased by 1, making a + x + 2=102
I coded a very simple neural net with 1 neuron and 2 inputs and 1 bias in java, trying to classify dots on either the left or right side of a line. The problem is that the neural net recognizes the slope of the line but not the y-intercept (e.g. the function of the line may be y = m*x + c and the NN recognizes the m but not the c).
I tried to use a bias value=1 in order to enable the NN to calculate the weight for the bias which should be the y-intercept. But it doesnt. You will see that I am very new to Java programming. Unfortunately also new to NN. In that case I guess my problem is rather in the understanding of the underlying methodology of the bias in the NN.
Remark: In the output line at the very end of the code, I would expect in case of the function y = 3*x + 5 following figures: weight[0]=3 (which is the m) , weight[1]=1 (which is the factor for y) and weight[2]=5 (this is c). The weight[2] is always wrong.
package nn2;
public class anfang_eng {
public static void main(String[] args)
{
double[][] points = new double[5][10000];
double[] weights = new double[3];
double[][] normpoints = new double[5][10000];
// create 1000 dots with desired result for training afterwards
points = createPoints();
// the before randomly created x and y values of the 1000 dots
// shall be normalized between 0 and 1
normpoints = normalize(points);
// create two random initial weights
weights = createinitialWeights();
// training function, calculation of three different weights
calculateWeights(normpoints, weights);
testnewPoints(weights);
}
// thats the function of the line, that seperates all dots in
// two groups: all the dots at the left side of the line and all the dots
// at the right side.
static double function(double x, double y)
{
double result;
result = 3*x - y + 5;
return result;
}
static double[][] createPoints()
{
// 1. step: lets create for training reasons some dots and calculate
// the result for each dot (result is either "1" or "-1").
// point[0] is x, point[1] is y, point[2] is bias and point[3] is
// result (left or right side of the function above
int x;
int y;
int quantity= 1000;
double[][] point = new double[5][quantity];
for (int i=0; i<quantity; i++)
{
x = (int) (2000 * Math.random()-1000);
y = (int) (2000 * Math.random()-1000);
point[0][i] = x;
point[1][i] = y;
// point[2] is our bias
point[2][i] = 1;
// all dots which are at the right side of the function above get
// result "1". otherwise "-1"
if ( function(x,y) > 0)
point[3][i] = 1;
else
point[3][i] =-1;
// point[3] contains the result
}
// in the variable point, there are e.g. 1000 or 5000 dots with x, y,
// bias and the result (1=left side and -1=right side)
return point;
}
// normalize x and y values between 0 and 1
static double[][] normalize(double[][]points)
{
int quantity = points[0].length;
double minpoint_x=1000;
double minpoint_y=1000;
double maxpoint_x=-1000;
double maxpoint_y=-1000;
double[][] normpoints = new double[5][quantity];
minpoint_x= points[0][0];
minpoint_y = points[1][0];
maxpoint_x = points[0][0];
maxpoint_y = points[1][0];
for (int i=0; i<quantity;i++)
{
if (points[0][i]<minpoint_x)
minpoint_x=points[0][i];
if (points[1][i]<minpoint_y)
minpoint_y=points[1][i];
if (points[0][i]>maxpoint_x)
maxpoint_x=points[0][i];
if (points[1][i]>maxpoint_y)
maxpoint_y=points[1][i];
}
for (int u=0; u<quantity; u++)
{
normpoints [0][u]= (points[0][u]-minpoint_x)/(maxpoint_x-minpoint_x);
normpoints [1][u]= (points[1][u]-minpoint_y)/(maxpoint_y-minpoint_y);
normpoints [2][u] = 1; //bias is always 1
normpoints [3][u] = points[3][u];
}
return normpoints;
}
static double[] createinitialWeights()
{
// creation of initial weights between -1 and 1
double[] weight = new double[3];
weight[0] = 2*Math.random()-1;
weight[1] = 2*Math.random()-1;
weight[2] = 2*Math.random()-1;
return weight;
}
static void calculateWeights(double[][] normpoints, double[] weight)
// new weight = weight + error * input * learning constant
// c is learning constant
{
double c = 0.01;
double error = 0;
double sumguess = 0;
double guess = 0;
int quantity = normpoints[0].length;
for (int i=0; i < quantity; i++)
{
// normpoint[0][i] stands for the factor at x, normpoint[0][i] is
// for y and normpoint[2][i] is for bias
sumguess = normpoints[0][i] * weight[0] + normpoints[1][i]*weight[1] + normpoints[2][i]*weight[2];
if (sumguess > 0)
guess = 1;
else
guess = -1;
error = normpoints[3][i]- guess;
weight[0] = weight[0] + error * normpoints[0][i] * c;
weight[1] = weight[1] + error * normpoints[1][i] * c;
weight[2] = weight[2] + error * normpoints[2][i] * c;
System.out.println("i: " + i + " ;value_normpoint[0]:" + normpoints[0][i]+ " ;value_normpoint[1]" + normpoints[1][i]+ " ;value_normpoint[2]" + normpoints[2][i] + " result:" + normpoints[3][i]);
System.out.println("weight[0]: " + Math.round(weight[0]*100)/100.0 + " ;weight[1]: " +Math.round(weight[1]*100)/100.0 + " ;weight[2]: " + Math.round(weight[2]*100)/100.0 );
System.out.println("guess: "+ guess+ " result " + normpoints[3][i] + " error: " + error);
System.out.println();
}
System.out.println("final weights: x: " + weight[0] + " y: "+ weight[1] + " bias: " +weight[2]);
System.out.println("final weights normalized on y=1: x:" + weight[0]/weight[1] + " y: "+ weight[1]/weight[1] + " bias: " +weight[2]/weight[1]);
}
// lets test if the trained weights classify the test dot on the correct side of the line y=4*x+3
// again 500 random dots with "x", "y" and "results" are created and tested if the NN calculated correct weights
static void testnewPoints(double[] weights)
{
int x;
int y;
double[][] testpoint = new double[5][10000];
double[][] normalizedtestpoint = new double[5][10000];
int quantity = 500;
double sumcheck = 0;
double sumtest = 0;
int correct = 0;
int wrong = 0;
for (int i=0; i<quantity; i++)
{
// calculation of test points with x and y between -100 and 100
x = (int) (200 * Math.random()-100);
y = (int) (200 * Math.random()-100);
testpoint[0][i] = x;
testpoint[1][i] = y;
testpoint[2][i] = 1;
// lets classify the points: at the rights side of the line the result for each point is "1", on the left side "-1"
if (function(x,y) > 0)
testpoint[3][i] = 1;
else
testpoint[3][i] = -1;
// punkt[3] is the result
}
normalizedtestpoint= normalize(testpoint);
// are the test points with our calculated weights classified on the correct side of the line?
for (int i=0; i<quantity; i++)
{
sumcheck = normalizedtestpoint[0][i] * weights[0] + normalizedtestpoint[1][i] * weights[1] + normalizedtestpoint[2][i] * weights[2];
if (sumcheck > 0)
sumtest = 1;
else
sumtest = -1;
if (sumtest == normalizedtestpoint[3][i])
correct++;
else
wrong++;
}
System.out.println("correct: "+ correct + " wrong: " + wrong);
}
}
Please let me also know if you see some major issues in my coding style, quite an beginner style I guess.
Many thanks in advance!
Lonko
I hope this isn't a horrifically obvious question, but I'm new to Java and I've been creating a compound interest calculator. I wan't to take all the values that the user inputs and compute them.
P = present value,
r = rate,
m = times compounded in a year,
t = years compounded.
A = the amount at the end of the term
A is what I'm looking for. The formula for compound interest is
A = P(1+r/m)^mt.
A = Math.pow((P*(1+r/m)),m*t);
System.out.println("The amount(A) equals "+A);
I feel that I may know why the computation isn't working right, but I don't know the right way.
This should solve your problem
double amount,Principal ;
int r,m,t;
Amount = Principal * Math.pow( (1+(r/m)) , m*t );
System.out.println("The amount(A) equals "+amount);
I believe you formula is incorrect. You need to write it like:
public static void main(String[] args) {
int p = 100;
int t = 5;
int r = 10;
int m = 2;
double amount = p * Math.pow(1 + (r / m), m * t);
double interest = amount - p;
System.out.println("Compond Interest is " + interest);
System.out.println("Amount is " + amount);
}
I'm looking for some method that takes or does not take parameters for calculate confidence interval.
I don't want the apache methods,
just a simple method or som type of code that does this.
My knowledge is restricted, it basically boils down to completing an online task against an expected set of answers (https://www.hackerrank.com/challenges/stat-warmup).
However, as far as I read up, there are mistakes in the given answer, and I'd like to correct these.
My source is pretty much wikipedia https://en.wikipedia.org/wiki/Confidence_interval#Basic_Steps
/**
*
* #return int[]{lower, upper}, i.e. int array with Lower and Upper Boundary of the 95% Confidence Interval for the given numbers
*/
private static double[] calculateLowerUpperConfidenceBoundary95Percent(int[] givenNumbers) {
// calculate the mean value (= average)
double sum = 0.0;
for (int num : givenNumbers) {
sum += num;
}
double mean = sum / givenNumbers.length;
// calculate standard deviation
double squaredDifferenceSum = 0.0;
for (int num : givenNumbers) {
squaredDifferenceSum += (num - mean) * (num - mean);
}
double variance = squaredDifferenceSum / givenNumbers.length;
double standardDeviation = Math.sqrt(variance);
// value for 95% confidence interval, source: https://en.wikipedia.org/wiki/Confidence_interval#Basic_Steps
double confidenceLevel = 1.96;
double temp = confidenceLevel * standardDeviation / Math.sqrt(givenNumbers.length);
return new double[]{mean - temp, mean + temp};
}
here is you go this is the code calculate Confidence Interval
/**
*
* #author alaaabuzaghleh
*/
public class TestCI {
public static void main(String[] args) {
int maximumNumber = 100000;
int num = 0;
double[] data = new double[maximumNumber];
// first pass: read in data, compute sample mean
double dataSum = 0.0;
while (num<maximumNumber) {
data[num] = num*10;
dataSum += data[num];
num++;
}
double ave = dataSum / num;
double variance1 = 0.0;
for (int i = 0; i < num; i++) {
variance1 += (data[i] - ave) * (data[i] - ave);
}
double variance = variance1 / (num - 1);
double standardDaviation= Math.sqrt(variance);
double lower = ave - 1.96 * standardDaviation;
double higher = ave + 1.96 * standardDaviation;
// print results
System.out.println("average = " + ave);
System.out.println("sample variance = " + variance);
System.out.println("sample standard daviation = " + standardDaviation);
System.out.println("approximate confidence interval");
System.out.println("[ " + lower + ", " + higher + " ]");
}
}
I have created a method to create some random double values for example 10 values : num1, num2, …num10 which sum of this 10 values is 1 : num1+num2+…+num10 = 1
My method is like the method in forum
Getting N random numbers that the sum is M :
private static double[] randSum(int n, double m) {
Random rand = new Random();
double randNums[] = new double[n], sum = 0;
for (int i = 0; i < randNums.length; i++) {
randNums[i] = rand.nextDouble();
sum += randNums[i];
}
for (int i = 0; i < randNums.length; i++) {
randNums[i] /= sum * m;
}
return randNums;
}
But this method create very long numbers like: 0.18593711849349975
I even used Math.round() method but with this method my numbers are 0.0, 0.5, 0.0 , …
I need numbers from 0.01 to 0.99 or 0.1 to 0.9. If I was using integer numbers I could do this with something like Random.nextInt(0.98) +0.01 , but nextDouble() method doesn’t accept parameters, how can I do this? Would you please help me? thanks
You could generate integers via nextInt, and then divide them by the required power of 10.
Generate nextDouble(); and round it using this method
public static double round(double d, int decimalPlace){
BigDecimal bd = new BigDecimal(Double.toString(d));
bd = bd.setScale(decimalPlace,BigDecimal.ROUND_HALF_UP);
return bd.doubleValue();
}
double d = 3.1537;
// output is 3.2
System.out.println(d + " : " + round(d, 1));
// output is 3.15
System.out.println(d + " : " + round(d, 2));
// output is 3.154
System.out.println(d + " : " + round(d, 3));
Source
Multiply your number by 100 and round the result. That will give you the original number with the insignificant digits stripped off. Then subsequently divide the result by 100 to get back to the original scale.
x = Math.round(x*100.0) / 100.0;
If you want to use 2 decimals, you could do it as follows:
private static double[] randSum(int n, double m){
double[] randoms = new double[n];
int valueLeft = (int) (m * 100);
for(int i = 0; i < n-1; i++){
int tempRand = (int)(Math.random() * valueLeft);
randoms[i] = (double)tempRand / 100;
valueLeft -= tempRand;
System.out.println(tempRand + " " + randoms[i] + " " + valueLeft);
}
randoms[n-1] = (double)valueLeft/100;
return randoms;
}