I want to actively calculate the moving average of stock data using the formula below:
public class Average {
private static double usdJpy;
private int counter = 1;
private double movingAverageUsdJpy_ = 100.5;
public void calculateAverage(){
ReadData myData = new ReadData();
usdGbp = myData.getUsdGbp();
usdJpy = myData.getUsdJpy();
System.out.println("Before: " + movingAverageUsdJpy_);
movingAverageUsdJpy_ = (counter * movingAverageUsdJpy_ + usdJpy) / (counter + 1);
counter++;
System.out.println("Moving Average: " + movingAverageUsdJpy_);
}
}
-> Counter is the number of elements in the array.
My question is since the stock data already has a moving average, I want to set my initial movingAverage value to that (e.g 97.883). However, every time I call my method, the latest value that my program calculated for the movingAverage will be overwritten by the initial value I have set earlier, hence giving me the wrong result. I can't really use final because the movingAverage needs to be updated each time I call the method so really stuck!
Is there a way to fix this problem??
Your formula is incorrect. If counter is the not-yet incremented value, then use
movingAverage = (counter * movingAverage + latestRate) / (counter + 1)
Then increment counter by 1. Note that if you want counter to be fixed in size (as is quite common when reporting financial data like this), then you need to keep that number of elements in memory.
You probably have something like:
class Something{
public int calculateAverage(){
int movingAverage = 98888;
//more code to count average
}
}
What you need to do is:
class Something{
private int myAverage = 98888;
public int calculateAverage(){
//code to calculate using myAverage variable;
}
}
Create a new private field used for storing the previous average. I'm not very familiar with moving averages per say, but using the formula you've provided I've adjusted things a bit. Note, typically an underscore is used to indicate that a class level variable is private
private double movingAverage_;
private double prevAverage_ = 97.883;
public void calculateMovingAverage()
{
movingAverage_ = prevAverage_ + (latestRate - prevAverage_)/counter;
prevAverage_ = movingAverage_;
// finish other logic
}
Related
I wanted to use the varags method to take the input of various integers and find out the maximum & minimum among them.
public class MINMAX {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int a = in.nextInt();
int b = in.nextInt();
int c = in.nextInt();
Maximum(a,b,c);
Minimum(a,b,c);
}
static void Maximum(int ...v) {
int max = Math.max(a,Math.max(b,c));
System.out.println("The Largest no. is: "+max);
}
static void Minimum(int ...v) {
int min = Math.min(a,Math.min(b,c));
System.out.println("The Smallest no. is: "+min);
}
}
Here, I'm taking input of a,b,c from the user to find out the max & min. but want to know how can i target the specific elements in Varargs Method.
To begin, imagine how many Math.min you need if you have 10 inputs instead of 3.
What you need is a method which can accept different number of inputs(that's why we have varargs), so that there is no need to change anything when you want to support more inputs. Hence you need to handle varargs(which can be treated as an array) instead of specific element.
In addition, by using IntStream#summaryStatistics, you can get min and max in one shot.
static void maximumAndMaximum(int... v) {
IntSummaryStatistics statistics = IntStream.of(v).summaryStatistics();
System.out.println("The Smallest no. is: " + statistics.getMin());
System.out.println("The Largest no. is: " + statistics.getMax());
}
You can access it as an int primitive type array that you have given in the method parameter.
e.g.
static void Maximum(int ...v) {
int max = Math.max(v[0],Math.max(v[1],v[2]));
System.out.println("The Largest no. is: "+max);
}
static void Minimum(int ...v) {
int min = Math.min(v[0],Math.min(v[1],v[2]));
System.out.println("The Smallest no. is: "+min);
}
I recommend that you make it a habit to check the size of the directory and other controls before starting the process.
The varargs syntax (... parameterName) is just another way of saying that the parameter is an array isn't it? The java.util.Collections class has methods on it that you might find useful. I suspect you may need to convert the array into something that implements the Collection interface to use them (e.g. java.util.ArrayList).
I'm learning app development for Android and have a small problem with my code. In the google tutorial i am working with we created a coffe ordering app. I did some extra coding for my plus and minus buttons, because i wanted them to update the price while changing the amount of cups ordered. That worked great, the moment i press the button the amount of cups and the total price get updated at the same time.
Now here comes my problem. I wanted to output a string with "Total: " + totalPrice, but that doesn't work and i found out why.
public void addCups(View view) {
numberOfCups = numberOfCups + 1;
display(numberOfCups);
displayMessage(gBetrag + endPreis);
}
Here are my global variables:
int numberOfCups = 0;
int priceOfCup = 5;
String message = "Vielen Dank!";
String gBetrag = "Gesamt: ";
String endPreis = NumberFormat.getCurrencyInstance().format(numberOfCups * priceOfCup);
I ran the code in debugging mode and found out that the method first looks for whats in "gBetrag" and "endPreis" before it updates the "numberOfCups" variable.
The output is "Gesamt: 0.00€" because endPreis is calculated before numberOfCups gets a +1. How do get java to execute the code in the order it was written or rather read the variable after it was updated?
I can workaround this issue if add the variable to every method i want to use it in, but that just adds more code and i tought that's why you use global variables.
You need to calculate the endPreis each time a cup is added:
public void addCups(View view) {
numberOfCups = numberOfCups + 1;
calculateTotal();
display(numberOfCups);
displayMessage(gBetrag + endPreis);
}
private void calculateTotal() {
endPreis = NumberFormat.getCurrencyInstance().format(numberOfCups * priceOfCup);
}
I suppose your class is written this way :
public class MyClass {
int numberOfCups = 0;
int priceOfCup = 5;
String message = "Vielen Dank!";
String gBetrag = "Gesamt: ";
String endPreis = NumberFormat.getCurrencyInstance().format(numberOfCups * priceOfCup);
public void addCups(View view) {
numberOfCups = numberOfCups + 1;
display(numberOfCups);
displayMessage(gBetrag + endPreis);
}
}
So here is how your code will be executed :
numberOfCups is set to 0
priceOfCup is set to 5
message is set
gBetrag is set
endPreis is set to (numberOfCups * priceOfCup)
When you call addCups(), it will display endPreis value.
As you could see, endPreis value was never re-calculated ;)
I'm confusing myself here. My goal was to make a simple program that took the number of values the user wants to average, store them in an array (while adding them together) and finally giving the average of these numbers.
My thing is, I am trying to understand the concept of multiple classes and methods as I am new so I tried using another class just do do all the work, while the Main class would just create the object from the other class, and then run their methods. Maybe I am asking something impossible. Take a look at my code.
This is my Main class:
public class Main
{
public static void main(String[] args)
{
System.out.println("Please enter numbers to average together");
OtherClass averages = new OtherClass();
averages.collectNumbers();
averages.AverageNumbers();
}
}
Now I am not sure if anything goes in those parameters, or if I can even use "averages.AverageNumbers();" without creating another object with "OtherClass" called something else? I am pretty sure it's legal though.
Here is my other class for this project entitled "OtherClass"
import java.util.Scanner;
public class OtherClass // using this to name obj
{
public void collectNumbers() //name of our method that does things
{
Scanner sc = new Scanner(System.in);
System.out.println("how many integers would you like to average? ");
int givenNum = sc.nextInt();
System.out.println("Alright, I will average " + givenNum + " values. \nPress enter after each:");
int[] numCollect = new int[givenNum];
int sum = 0;
for (int i = 0; i < numCollect.length; i++)
{
numCollect[i] = sc.nextInt();
sum = sum + numCollect[i];
}
System.out.println(sum);
}
public int AverageNumbers(int givenNum, int sum)
{
int average = sum / givenNum;
System.out.println(average);
return average;
}
}
So when I run this now with the the method AverageNumbers, it does not work. I am suspecting that maybe I am passing in the integers wrong? I have been toying with it for about an hour now, so I am asking for help. How do I make this work?
This will work if you declare sum and givenNum as fields of your OtherClass, instead of as local variables. So, before the collectNumbers method, write
private int sum;
private int givenNum;
and remove the declarations of these two variables inside collectNumbers. So, for example, instead of
int givenNum = sc.getInt();
you'll just have
givenNum = sc.getInt();
because the variable already exists. Also change the declaration of the averageNumbers method to
public int averageNumbers()
because you no longer need to pass those two values in to this method.
This is the archetypical example of using the objects of a class to carry a small amount of data around, instead of just using a class as a way to group methods together. The two methods of this class work with sum and givenNum, so it makes sense to store these in each object of this class.
Lastly, in your averageNumbers method, you have an integer division, which will automatically round down. You probably want a floating point division instead, so you could write
double average = (double) sum / givenNum;
which converts sum to a double-precision floating point number before the division, and therefore does the division in floating point, instead of just using integers. Of course, if you make this change, you'll need to change the return type of this method to double too.
I want to create a unique number of "Long" type using java. I have seen few examples but they were using timestamp, without using timestamp can i create a unique number of wrapper object "Long" .Please suggest.
please suggest.Thanks.
Generate each digit by calling random.nextInt. For uniqueness, you can keep track of the random numbers you have used so far by keeping them in a set and checking if the set contains the number you generate each time.
public static long generateRandom(int length) {
Random random = new Random();
char[] digits = new char[length];
digits[0] = (char) (random.nextInt(9) + '1');
for (int i = 1; i < length; i++) {
digits[i] = (char) (random.nextInt(10) + '0');
}
return Long.parseLong(new String(digits));
}
Without using timestamp, you have these options:
Keep a record of all previously generated numbers -- of course you have to store them somewhere, which is unwieldy
Store the previous number, and increment each time.
Simply assume that the PRNG will never come up with the same number twice. Since there are 2^64 == 1.8 * 10^19 possible values, this is a very safe bet.
Many of the answers suggest using Math.random() to generate the unique id. Now Math.random() is actually not random at all, and does in itself not add anything unique. The seemingly uniqueness comes from the default seeding in the Math.random() based on System.currentTimeMillis(); with the following code:
/**
* Construct a random generator with the current time of day in milliseconds
* as the initial state.
*
* #see #setSeed
*/
public Random() {
setSeed(System.currentTimeMillis() + hashCode());
}
So why not just remove the Math.Random() from the equation and just use System.currentTimeMillis() in the counter.
Time based unique numbers:
The following code implements a unique number generator based solemnly on time. The benefit of this is that you don't need to store any counters etc. The numbers generated will be unique under the following condition: The code only runs in one JVM at any time periode - this is important, as the timestamp is part of the key.
public class UniqueNumber {
private static UniqueNumber instance = null;
private long currentCounter;
private UniqueNumber() {
currentCounter = (System.currentTimeMillis() + 1) << 20;
}
private static synchronized UniqueNumber getInstance() {
if (instance == null) {
instance = new UniqueNumber();
}
return instance;
}
private synchronized long nextNumber() {
currentCounter++;
while (currentCounter > (System.currentTimeMillis() << 20)) {
try {
Thread.sleep(1);
} catch (InterruptedException e) {
}
}
return currentCounter;
}
static long getUniqueNumber() {
return getInstance().nextNumber();
}
}
The code allows for up to 2^20 numbers to be generated per millisecond (provided you have access to that fast hardware). If this rate is exceeded the code will sleep until next tick of System.currentTimeMillis()
Testing the code:
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
System.out.println(UniqueNumber.getUniqueNumber());
}
}
Output:
1472534126716256257
1472534126716256258
1472534126716256259
1472534126716256260
1472534126716256261
1472534126716256262
1472534126716256263
1472534126716256264
1472534126716256265
1472534126716256266
Take a look on this Commons Id, it has LongGenerator that generates an incrementing number as a Long object.
This will create simply a random long number -
System.out.println((long)((Math.random())*1000000000000000000L));
You can generate random numbers using java.util.Random and add them to a java.util.Set this will ensure that no duplicate is allowed
Try with UUID as:
Long uniqueLong = UUID.randomUUID().getMostSignificantBits();
Here, you find a very good explanation as to why this could be unique in terms of randomness.
I'm new to OO programing and having a bit of trouble with the design of my program to use the concepts. I have done the tutorials but am still having problem.
I have a recursion that takes a value of items(could be anything in this example, stocks) and figures out what number of them are needed to equal a specific value(in this code 100). This part works but I want to know if a stock's weighting exceeds a threshold. Originally I approached this problem with a method that did a for loop and calculated the entire list of values but this is super inefficient because its doing it on every loop of the recursion. I thought this would be a good time to try to learn classes because I could use a class to maintain state information and just increment the value on each loop and it'll let me know when the threshold is hit.
I think I have the code but I don't fully understand how to design this problem with classes. So far it runs the loop each step of the recursion because I'm initially the class there. Is there a better way to design this? My end goal is to be notified when a weighting is exceeded(which I can somewhat already do) but I want to do in way that uses the least bit of resources(avoiding inefficient/unnecessary for loops)
Code(Here's the entire code I have been using to learn but the problem is with the Counter class and its location within the findVariables method):
import java.util.Arrays;
public class LearningClassCounting {
public static int[] stock_price = new int[]{ 20,5,20};
public static int target = 100;
public static void main(String[] args) {
// takes items from the first list
findVariables(stock_price, 100, new int[] {0,0,0}, 0, 0);
}
public static void findVariables(int[] constants, int sum,
int[] variables, int n, int result) {
Counter Checker = new Counter(stock_price, variables);
if (n == constants.length) {
if (result == sum) {
System.out.println(Arrays.toString(variables));
}
} else if (result <= sum){ //keep going
for (int i = 0; i <= 100; i++) {
variables[n] = i;
Checker.check_total_percent(n, i);
findVariables(constants, sum, variables, n+1, result+constants[n]*i);
}
}
}
}
class Counter {
private int[] stock_price;
private int[] variables;
private int value_so_far;
public Counter(int[] stock_price, int[] variables) {
this.stock_price = stock_price;
this.variables = variables;
for (int location = 0; location < variables.length; location++) {
//System.out.println(variables[location] + " * " + stock_price[location] + " = " + (variables[location] * stock_price[location]) );
value_so_far = value_so_far + (variables[location] * stock_price[location]);
}
//System.out.println("Total value so far is " + value_so_far);
//System.out.println("************");
}
public void check_total_percent(int current_location, int percent) {
// Check to see if weight exceeds threshold
//System.out.println("we are at " + current_location + " and " + percent + " and " + Arrays.toString(variables));
//System.out.println("value is " + stock_price[current_location] * percent);
//formula I think I need to use is:
if (percent == 0) {
return;
}
int current_value = (stock_price[current_location] * percent);
int overall_percent = current_value/(value_so_far + current_value);
if (overall_percent > 50 ) {
System.out.println("item " + current_location + " is over 50%" );
}
}
}
What you're describing sounds like a variant of the famous knapsack problem. There are many approaches to these problems, which are inherently difficult to calculate.
Inherently, one may need to check "all the combinations". The so-called optimization comes from backtracking when a certain selection subset is already too large (e.g., if 10 given stocks are over my sum, no need to explore other combinations). In addition, one can cache certain subsets (e.g., if I know that X Y and Z amount to some value V, I can reuse that value). You'll see a lot of discussion of how to approach these sort of problems and how to design solutions.
That being said, my view is that while algorithmic problems of this sort may be important for learning how to program and structure code and data structures, they're generally a very poor choice for learning object-oriented design and modelling.