Java - how to make these methods multithreaded? [closed] - java

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
Current code is single-threaded. It reads data from file, generate random numbers and check if that numbers belong to given interval.
import java.io.*;
import java.util.*;
class Generator {
private double mean;
private double variance;
private long amountOfNumbersToGenerate;
public Generator(double mean, double variance, long amountOfNumbersToGenerate) {
this.mean = mean;
this.variance = variance;
this.amountOfNumbersToGenerate = amountOfNumbersToGenerate;
}
double getMean() {
return mean;
}
double getVariance() {
return variance;
}
long getAmountOfNumbersToGenerate() {
return amountOfNumbersToGenerate;
}
}
class Interval {
private double start;
private double end;
public Interval(double start, double end) {
this.start = start;
this.end = end;
}
double getStart() {
return start;
}
double getEnd() {
return end;
}
}
class ParsedData {
private Vector<Generator> generators;
private Vector<Interval> intervals;
public ParsedData(Vector<Generator> generators, Vector<Interval> intervals) {
this.generators = generators;
this.intervals = intervals;
}
Vector<Generator> getGenerators() {
return generators;
}
Vector<Interval> getIntervals() {
return intervals;
}
}
class Worker extends Thread {
public Worker() {
}
}
class Start {
static ParsedData readDataFromFile(String path) throws IOException {
File file = new File(path);
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
line = br.readLine();
String delimiter = "\\s+";
// generators
long generatorSize = Long.parseLong(line);
Vector<Generator> generators = new Vector<Generator>();
for(long i =0; i < generatorSize; i++) {
line = br.readLine();
Scanner f = new Scanner(line);
f.useLocale(Locale.US); //without this line the program wouldn't work on machines with different locales
f.useDelimiter(delimiter);
Generator g = new Generator(f.nextDouble(), f.nextDouble(), f.nextInt());
generators.add(g);
}
line = br.readLine();
long intervalSize = Long.parseLong(line);
Vector<Interval> intervals = new Vector<Interval>();
for(long i = 0; i < intervalSize; i++) {
line = br.readLine();
System.out.println(line);
Scanner f = new Scanner(line);
f.useLocale(Locale.US); //without this line the program wouldn't work on machines with different locales
f.useDelimiter(delimiter);
Interval interval = new Interval(f.nextDouble(), f.nextDouble());
intervals.add(interval);
}
br.close();
return new ParsedData(generators, intervals);
}
static double boxMullerMarsagliaPolarRand(double mean, double variance) {
double micro = mean;
double sigma = Math.sqrt(variance);
double y, x, omega;
Random random = new Random();
do {
x = random.nextDouble();
y = random.nextDouble();
omega = x * x + y * y;
} while (!(0.0 < omega && omega < 1.0));
double sigma_sqrt = sigma * Math.sqrt(-2.0 * Math.log(omega) / omega);
double g = micro + x * sigma_sqrt;
// float h = micro + y * sigma_sqrt;
return g;
}
/////////////////////////////////////////
// TODO: refactor code into multithreaded
static Vector<Double> generateRandomNumbers(ParsedData parsedData) {
Vector<Double> generatedNumbers = new Vector<Double>();
for(int i = 0; i < parsedData.getGenerators().size(); i++) {
Generator g = parsedData.getGenerators().get(i);
for(long j = 0; j < g.getAmountOfNumbersToGenerate(); j++) {
double random = boxMullerMarsagliaPolarRand(g.getMean(), g.getVariance());
generatedNumbers.add(random);
}
}
return generatedNumbers;
}
/////////////////////////////////////////
// TODO: refactor code into multithreaded
static int[] checkIntervals(ParsedData parsedData, Vector<Double> generatedNumbers) {
int[] numberOfHits = new int[parsedData.getIntervals().size()];
for(int j = 0; j < parsedData.getIntervals().size(); j++) {
Interval interval = parsedData.getIntervals().get(j);
for(int i = 0; i < generatedNumbers.size(); i++) {
if (interval.getStart() < generatedNumbers.get(i) && generatedNumbers.get(i) < interval.getEnd()) {
numberOfHits[j]++;
}
}
}
return numberOfHits;
}
public static void main(String args[]) {
int amountOfThreads = Integer.parseInt(args[0]);
String path = System.getProperty("user.dir") + "/input.dat";
ParsedData parsedData = null;
try {
parsedData = readDataFromFile(path);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(parsedData.getGenerators().size());
System.out.println(parsedData.getIntervals().size());
Vector<Double> generatedNumbers = generateRandomNumbers(parsedData);
int[] numberOfHits = checkIntervals(parsedData, generatedNumbers);
for (int i = 0; i < numberOfHits.length; i++) {
Interval interval = parsedData.getIntervals().get(i);
System.out.println("" + (i+1) + " " + interval.getStart() + " " + interval.getEnd() + " " + numberOfHits[i]);
}
System.out.println(generatedNumbers.size());
}
}
I don't expect for anyone to write/refactor code for me.
But I don't know how to make this methods multi-threaded:
/////////////////////////////////////////
// TODO: refactor code into multithreaded
static Vector<Double> generateRandomNumbers(ParsedData parsedData) {
Vector<Double> generatedNumbers = new Vector<Double>();
for(int i = 0; i < parsedData.getGenerators().size(); i++) {
Generator g = parsedData.getGenerators().get(i);
for(long j = 0; j < g.getAmountOfNumbersToGenerate(); j++) {
double random = boxMullerMarsagliaPolarRand(g.getMean(), g.getVariance());
generatedNumbers.add(random);
}
}
return generatedNumbers;
}
/////////////////////////////////////////
// TODO: refactor code into multithreaded
static int[] checkIntervals(ParsedData parsedData, Vector<Double> generatedNumbers) {
int[] numberOfHits = new int[parsedData.getIntervals().size()];
for(int j = 0; j < parsedData.getIntervals().size(); j++) {
Interval interval = parsedData.getIntervals().get(j);
for(int i = 0; i < generatedNumbers.size(); i++) {
if (interval.getStart() < generatedNumbers.get(i) && generatedNumbers.get(i) < interval.getEnd()) {
numberOfHits[j]++;
}
}
}
return numberOfHits;
}

The easiest way to make this multithreaded is to use a producer-consumer pattern, with one producer reading the data and sending it to a BlockingQueue, and the consumers reading the data from the BlockingQueue (using take) and processing it using your two static methods. This way you need to do minimal refactoring - the static methods are already re-entrant / thread-safe (assuming that the Vector and ParsedData parameters aren't shared), so they don't need to be modified at all.

Related

MLFQ only functions when other class runs

I have a multi-level feedback class which I am not sure what its doing - it only ever seems to print the output I want when I run a pre-emptive multi-level class before it, when I don't it prints a different output. I am not sure how these are connected and making this happen.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class MultiLevelFeedback {
List<Process> processList;
private int timeQuantum1;
private int timeQuantum2;
private int count;
int j=0;
private int ganntP[];
private int ganntT[];
private int totalWaitingTime = 0;
private int totalTurnAroundTime = 0;
private float avgWatingTime = 0;
private float avgTurnaroundTime = 0;
MultiLevelFeedback(List<Process> processList, int timeQuantum1,int timeQuantum2) {
count = processList.size();
ganntT=new int[200];
ganntP=new int[200];
this.timeQuantum1 = timeQuantum1;
this.timeQuantum2 = timeQuantum2;
this.processList=new ArrayList<Process>();
for(Process p : processList)
{
this.processList.add(new Process(p.getProcessId(), p.getArrivalTime(), p.getBurstTime(),p.getPriority()));
}
Collections.sort(this.processList, Process.BY_PRIORITY);
}
public void simulate() {
int currentTime =0;
int remainingProcess = count;
while (remainingProcess > processList.size()/2)
{
int clockTime=currentTime;
for (int i = 0; i < count; i++)
{
Process current = processList.get(i);
if(currentTime<current.getArrivalTime())
break;
if (current.getStartTime() == -1)
current.setStartTime(currentTime);
ganntP[j]=current.getProcessId();
ganntT[j]=currentTime;
j++;
if (current.getRemainingTime() <= timeQuantum1 && current.getEndTime()==-1)
{
current.setEndTime(currentTime + current.getRemainingTime());
currentTime += current.getRemainingTime();
current.setRemainingTime(0);
remainingProcess--;
}
else if (current.getRemainingTime()>timeQuantum1)
{
currentTime += timeQuantum1;
current.setRemainingTime(current.getRemainingTime()-timeQuantum1);
}
}
if(clockTime==currentTime)
{
currentTime++;
}
}
while (remainingProcess > processList.size()/2)
{
int clockTime=currentTime;
for (int i = 0; i < count; i++)
{
Process current = processList.get(i);
if(currentTime<current.getArrivalTime())
break;
if (current.getStartTime() == -1)
current.setStartTime(currentTime);
ganntP[j]=current.getProcessId();
ganntT[j]=currentTime;
j++;
if (current.getRemainingTime() <= timeQuantum2 && current.getEndTime()==-1)
{
current.setEndTime(currentTime + current.getRemainingTime());
currentTime += current.getRemainingTime();
current.setRemainingTime(0);
remainingProcess--;
}
else if (current.getRemainingTime()>timeQuantum2)
{
currentTime += timeQuantum2;
current.setRemainingTime(current.getRemainingTime()-timeQuantum2);
}
}
if(clockTime==currentTime)
{
currentTime++;
}
}
for(int i=0;i<count;i++)
{
Process current=processList.get(i);
if(current.getRemainingTime()>0 )
{
if(currentTime<current.getArrivalTime())
{
currentTime=current.getArrivalTime();
current.setStartTime(currentTime);
}
current.setEndTime(currentTime+current.getRemainingTime());
currentTime+=current.getRemainingTime();
}
}
for (int i = 0; i < count; i++)
{
Process current = processList.get(i);
current.setWaitingTime(current.getEndTime()-current.getBurstTime()-current.getArrivalTime());
current.setTurnaroundTime(current.getEndTime() - current.getArrivalTime());
totalWaitingTime += current.getWaitingTime();
totalTurnAroundTime += current.getTurnaroundTime();
}
avgWatingTime = (float) totalWaitingTime / count;
avgTurnaroundTime = (float) totalTurnAroundTime / count;
}
public void printResult()
{
System.out.println("Simulation result of MultiLevelFeedback ");
System.out.println("PId ArrivalT BurstT Priority StartT EndT WaitingT TurnAroundT");
for (Process p : processList)
{
System.out.println(p);
}
System.out.println("Average Waiting Time of MultiLevelFeedback "
+ avgWatingTime);
System.out.println("Average TurnAround Time of MultiLevelFeedback "
+ avgTurnaroundTime);
for(int i=0;i<j;i++)
{
System.out.println("time "+ganntT[i]+" process "+ganntP[i]);
}
System.out.println();
}
}
I am confused as there's nothing in the mlfq class which has anything to do with the pre-emptive multi-level class - they are both separate algorithms - except it is differing the output when I run both.

How to use the saved neural network.ser in Android studio

I've trained a neural network in NetBeans and saved it as neural_network.ser by using Serializable ,"all classes implement Serializable" , Now I want to use it in my android application but when loading the network ,ClassNotFoundException raised .
java.lang.ClassNotFoundException: neural_network.BackPropagation
Here is the Classes:
BackPropagation class:
public class BackPropagation extends Thread implements Serializable
{
private static final String TAG = "NetworkMessage";
private static final long serialVersionUID = -8862858027413741101L;
private double OverallError;
// The minimum Error Function defined by the user
private double MinimumError;
// The user-defined expected output pattern for a set of samples
private double ExpectedOutput[][];
// The user-defined input pattern for a set of samples
private double Input[][];
// User defined learning rate - used for updating the network weights
private double LearningRate;
// Users defined momentum - used for updating the network weights
private double Momentum;
// Number of layers in the network
private int NumberOfLayers;
// Number of training sets
private int NumberOfSamples;
// Current training set/sample that is used to train network
private int SampleNumber;
// Maximum number of Epochs before the traing stops training
private long MaximumNumberOfIterations;
// Public Variables
public LAYER Layer[];
public double ActualOutput[][];
long delay = 0;
boolean die = false;
// Calculate the node activations
public void FeedForward()
{
int i,j;
// Since no weights contribute to the output
// vector from the input layer,
// assign the input vector from the input layer
// to all the node in the first hidden layer
for (i = 0; i < Layer[0].Node.length; i++)
Layer[0].Node[i].Output = Layer[0].Input[i];
Layer[1].Input = Layer[0].Input;
for (i = 1; i < NumberOfLayers; i++)
{
Layer[i].FeedForward();
// Unless we have reached the last layer, assign the layer i's //output vector
// to the (i+1) layer's input vector
if (i != NumberOfLayers-1)
Layer[i+1].Input = Layer[i].OutputVector();
}
}
// FeedForward()
// Back propagated the network outputy error through
// the network to update the weight values
public void UpdateWeights()
{
CalculateSignalErrors();
BackPropagateError();
}
private void CalculateSignalErrors()
{
int i,j,k,OutputLayer;
double Sum;
OutputLayer = NumberOfLayers-1;
// Calculate all output signal error
for (i = 0; i < Layer[OutputLayer].Node.length; i++)
{
Layer[OutputLayer].Node[i].SignalError =
(ExpectedOutput[SampleNumber][i] -Layer[OutputLayer].Node[i].Output) *
Layer[OutputLayer].Node[i].Output *
(1-Layer[OutputLayer].Node[i].Output);
}
// Calculate signal error for all nodes in the hidden layer
// (back propagate the errors
for (i = NumberOfLayers-2; i > 0; i--)
{
for (j = 0; j < Layer[i].Node.length; j++)
{
Sum = 0;
for (k = 0; k < Layer[i+1].Node.length; k++)
Sum = Sum + Layer[i+1].Node[k].Weight[j] *
Layer[i+1].Node[k].SignalError;
Layer[i].Node[j].SignalError = Layer[i].Node[j].Output*(1 -
Layer[i].Node[j].Output)*Sum;
}
}
}
private void BackPropagateError()
{
int i,j,k;
// Update Weights
for (i = NumberOfLayers-1; i > 0; i--)
{
for (j = 0; j < Layer[i].Node.length; j++)
{
// Calculate Bias weight difference to node j
Layer[i].Node[j].ThresholdDiff = LearningRate *
Layer[i].Node[j].SignalError +
Momentum*Layer[i].Node[j].ThresholdDiff;
// Update Bias weight to node j
Layer[i].Node[j].Threshold =
Layer[i].Node[j].Threshold +
Layer[i].Node[j].ThresholdDiff;
// Update Weights
for (k = 0; k < Layer[i].Input.length; k++)
{
// Calculate weight difference between node j and k
Layer[i].Node[j].WeightDiff[k] =
LearningRate *
Layer[i].Node[j].SignalError*Layer[i-
1].Node[k].Output +
Momentum*Layer[i].Node[j].WeightDiff[k];
// Update weight between node j and k
Layer[i].Node[j].Weight[k] =
Layer[i].Node[j].Weight[k] +
Layer[i].Node[j].WeightDiff[k];
}
}
}
}
private void CalculateOverallError()
{
int i,j;
OverallError = 0;
for (i = 0; i < NumberOfSamples; i++)
for (j = 0; j < Layer[NumberOfLayers-1].Node.length; j++)
{
OverallError = OverallError +
0.5*( Math.pow(ExpectedOutput[i][j] - ActualOutput[i]
[j],2) );
}
}
public BackPropagation(int NumberOfNodes[],
double InputSamples[][],
double OutputSamples[][],
double LearnRate,
double Moment,
double MinError,
long MaxIter
)
{
int i,j;
// Initiate variables
NumberOfSamples = InputSamples.length;
MinimumError = MinError;
LearningRate = LearnRate;
Momentum = Moment;
NumberOfLayers = NumberOfNodes.length;
MaximumNumberOfIterations = MaxIter;
// Create network layers
Layer = new LAYER[NumberOfLayers];
// Assign the number of node to the input layer
Layer[0] = new LAYER(NumberOfNodes[0],NumberOfNodes[0]);
// Assign number of nodes to each layer
for (i = 1; i < NumberOfLayers; i++)
Layer[i] = new LAYER(NumberOfNodes[i],NumberOfNodes[i-1]);
Input = new double[NumberOfSamples][Layer[0].Node.length];
ExpectedOutput = new double[NumberOfSamples][Layer[NumberOfLayers-
1].Node.length];
ActualOutput = new double[NumberOfSamples][Layer[NumberOfLayers-
1].Node.length];
// Assign input set
for (i = 0; i < NumberOfSamples; i++)
for (j = 0; j < Layer[0].Node.length; j++)
Input[i][j] = InputSamples[i][j];
// Assign output set
for (i = 0; i < NumberOfSamples; i++)
for (j = 0; j < Layer[NumberOfLayers-1].Node.length; j++)
ExpectedOutput[i][j] = OutputSamples[i][j];
}
public void TrainNetwork()
{
int i,j;
long k=0;
do
{
// For each pattern
for (SampleNumber = 0; SampleNumber < NumberOfSamples; SampleNumber++)
{
for (i = 0; i < Layer[0].Node.length; i++)
Layer[0].Input[i] = Input[SampleNumber][i];
FeedForward();
// Assign calculated output vector from network to ActualOutput
for (i = 0; i < Layer[NumberOfLayers-1].Node.length; i++)
ActualOutput[SampleNumber][i] = Layer[NumberOfLayers-
1].Node[i].Output;
UpdateWeights();
// if we've been told to stop training, then
// stop thread execution
if (die){
return;
}
// if
}
k++;
// Calculate Error Function
CalculateOverallError();
System.out.println("OverallError =
"+Double.toString(OverallError)+"\n");
System.out.print("Epoch = "+Long.toString(k)+"\n");
} while ((OverallError > MinimumError) &&(k < MaximumNumberOfIterations));
}
public LAYER[] get_layers() { return Layer; }
// called when testing the network.
public double[] test(double[] input)
{
int winner = 0;
NODE[] output_nodes;
for (int j = 0; j < Layer[0].Node.length; j++)
{ Layer[0].Input[j] = input[j];}
FeedForward();
// get the last layer of nodes (the outputs)
output_nodes = (Layer[Layer.length - 1]).get_nodes();
double[] actual_output = new double[output_nodes.length];
for (int k=0; k < output_nodes.length; k++)
{
actual_output[k]=output_nodes[k].Output;
} // for
return actual_output;
}//test()
public double get_error()
{
CalculateOverallError();
return OverallError;
} // get_error()
// to change the delay in the network
public void set_delay(long time)
{
if (time >= 0) {
delay = time;
} // if
}
//save the trained network
public void save(String FileName)
{
try{
FileOutputStream fos = new FileOutputStream (new File(FileName), true);
// Serialize data object to a file
ObjectOutputStream os = new ObjectOutputStream(fos);
os.writeObject(this);
os.close();
fos.close();
System.out.println("Network Saved!!!!");
}
catch (IOException E){System.out.println(E.toString());}
catch (Exception e){System.out.println(e.toString());}
}
public BackPropagation load(String FileName)
{
BackPropagation myclass= null;
try
{
//File patternDirectory = new File(Environment.getExternalStorageDirectory().getAbsolutePath().toString()+"INDIAN_NUMBER_RECOGNITION.data");
//patternDirectory.mkdirs();
FileInputStream fis = new FileInputStream(new File(FileName));
//FileInputStream fis =context.openFileInput(FileName);
ObjectInputStream is = new ObjectInputStream(fis);
myclass = (BackPropagation) is.readObject();
System.out.println("Error After Reading = "+Double.toString(myclass.get_error())+"\n");
is.close();
fis.close();
return myclass;
}
catch (Exception e){System.out.println(e.toString());}
return myclass;
}
// needed to implement threading.
public void run() {
TrainNetwork();
File Net_File = new File(Environment.getExternalStorageDirectory(),"Number_Recognition_1.ser");
save(Net_File.getAbsolutePath());
System.out.println( "DONE TRAINING :) ^_^ ^_^ :) !\n");
System.out.println("With Network ERROR = "+Double.toString(get_error())+"\n");
} // run()
// to notify the network to stop training.
public void kill() { die = true; }
}
Layer Class:
public class LAYER implements Serializable
{
private double Net;
public double Input[];
// Vector of inputs signals from previous
// layer to the current layer
public NODE Node[];
// Vector of nodes in current layer
// The FeedForward function is called so that
// the outputs for all the nodes in the current
// layer are calculated
public void FeedForward() {
for (int i = 0; i < Node.length; i++) {
Net = Node[i].Threshold;
for (int j = 0; j < Node[i].Weight.length; j++)
{Net = Net + Input[j] * Node[i].Weight[j];
System.out.println("Net = "+Double.toString(Net)+"\n");
}
Node[i].Output = Sigmoid(Net);
System.out.println("Node["+Integer.toString(i)+".Output = "+Double.toString(Node[i].Output)+"\n");
}
}
// The Sigmoid function calculates the
// activation/output from the current node
private double Sigmoid (double Net) {
return 1/(1+Math.exp(-Net));
}
// Return the output from all node in the layer
// in a vector form
public double[] OutputVector() {
double Vector[];
Vector = new double[Node.length];
for (int i=0; i < Node.length; i++)
Vector[i] = Node[i].Output;
return (Vector);
}
public LAYER (int NumberOfNodes, int NumberOfInputs) {
Node = new NODE[NumberOfNodes];
for (int i = 0; i < NumberOfNodes; i++)
Node[i] = new NODE(NumberOfInputs);
Input = new double[NumberOfInputs];
}
// added by DSK
public NODE[] get_nodes() { return Node; }
}
Node Class:
public class NODE implements Serializable
{
public double Output;
// Output signal from current node
public double Weight[];
// Vector of weights from previous nodes to current node
public double Threshold;
// Node Threshold /Bias
public double WeightDiff[];
// Weight difference between the nth and the (n-1) iteration
public double ThresholdDiff;
// Threshold difference between the nth and the (n-1) iteration
public double SignalError;
// Output signal error
// InitialiseWeights function assigns a randomly
// generated number, between -1 and 1, to the
// Threshold and Weights to the current node
private void InitialiseWeights() {
Threshold = -1+2*Math.random();
// Initialise threshold nodes with a random
// number between -1 and 1
ThresholdDiff = 0;
// Initially, ThresholdDiff is assigned to 0 so
// that the Momentum term can work during the 1st
// iteration
for(int i = 0; i < Weight.length; i++) {
Weight[i]= -1+2*Math.random();
// Initialise all weight inputs with a
// random number between -1 and 1
WeightDiff[i] = 0;
// Initially, WeightDiff is assigned to 0
// so that the Momentum term can work during
// the 1st iteration
}
}
public NODE (int NumberOfNodes) {
Weight = new double[NumberOfNodes];
// Create an array of Weight with the same
// size as the vector of inputs to the node
WeightDiff = new double[NumberOfNodes];
// Create an array of weightDiff with the same
// size as the vector of inputs to the node
InitialiseWeights();
// Initialise the Weights and Thresholds to the node
}
public double[] get_weights() { return Weight; }
public double get_output() { return Output; }
}
I wrote the code in Netbeans exactly like this but it differs in the saving method where the file should be saved!.
How can I load the file correctly so I don't get this exception?
I Solved this by saving the network to XML file and then load it again in android so it just took two hours of training instead of days without any Serialization problems , although it took some time to load that XML I serialized it again to neural_network.ser so it will load much faster
I know it's not the best solution but that what I've done.
Here the is the code:
public void SaveToXML(String FileName)throws
ParserConfigurationException, FileNotFoundException,
TransformerException, TransformerConfigurationException
{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder parser = factory.newDocumentBuilder();
Document doc = parser.newDocument();
Element root = doc.createElement("neuralNetwork");
Element layers = doc.createElement("structure");
layers.setAttribute("numberOfLayers",Integer.toString(this.NumberOfLayers));
for (int il=0; il<this.NumberOfLayers; il++){
Element layer = doc.createElement("layer");
layer.setAttribute("index",Integer.toString(il));
layer.setAttribute("numberOfNeurons",Integer.toString(this.Layer[il].Node.length));
if(il==0)
{
for(int in=0;in<this.Layer[il].Node.length;in++)
{
Element neuron = doc.createElement("neuron");
neuron.setAttribute("index",Integer.toString(in));
neuron.setAttribute("NumberOfInputs",Integer.toString(1));
neuron.setAttribute("threshold",Double.toString(this.Layer[il].Node[in].Threshold));
Element input = doc.createElement("input");
double[] weights = this.Layer[il].Node[in].get_weights();
input.setAttribute("index",Integer.toString(in));
input.setAttribute("weight",Double.toString(weights[in]));
neuron.appendChild(input);
layer.appendChild(neuron);
}
layers.appendChild(layer);
}
else
{
for (int in=0; in<this.Layer[il].Node.length;in++){
Element neuron = doc.createElement("neuron");
neuron.setAttribute("index",Integer.toString(in));
neuron.setAttribute("NumberOfInputs",Integer.toString(this.Layer[il].Node[in].Weight.length));
neuron.setAttribute("threshold",Double.toString(this.Layer[il].Node[in].Threshold));
for (int ii=0; ii<this.Layer[il].Node[in].Weight.length;ii++) {
double[] weights = this.Layer[il].Node[in].get_weights();
Element input = doc.createElement("input");
input.setAttribute("index",Integer.toString(ii));
input.setAttribute("weight",Double.toString(weights[ii]));
neuron.appendChild(input);
}
layer.appendChild(neuron);
layers.appendChild(layer);
}
}
}
root.appendChild(layers);
doc.appendChild(root);
File xmlOutputFile = new File(FileName);
FileOutputStream fos;
Transformer transformer;
fos = new FileOutputStream(xmlOutputFile);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(fos);
transformer.setOutputProperty("encoding","iso-8859-2");
transformer.setOutputProperty("indent","yes");
transformer.transform(source, result);
}
LoadFromXML Function:
public BackPropagation LoadFromXML(String FileName)throws
ParserConfigurationException, SAXException, IOException, ParseException
{
BackPropagation myclass= new BackPropagation();
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder parser = factory.newDocumentBuilder();
File source = new File(FileName);
Document doc = parser.parse(source);
Node nodeNeuralNetwork = doc.getDocumentElement();
if (!nodeNeuralNetwork.getNodeName().equals("neuralNetwork")) throw new ParseException("[Error] NN-Load: Parse error in XML file, neural network couldn't be loaded.",0);
NodeList nodeNeuralNetworkContent = nodeNeuralNetwork.getChildNodes();
System.out.print("<neuralNetwork>\n");
for (int innc=0; innc<nodeNeuralNetworkContent.getLength(); innc++)
{
Node nodeStructure = nodeNeuralNetworkContent.item(innc);
if (nodeStructure.getNodeName().equals("structure"))
{
System.out.print("<stucture nuumberOfLayers = ");
myclass.NumberOfLayers = Integer.parseInt(((Element)nodeStructure).getAttribute("numberOfLayers"));
myclass.Layer = new LAYER[myclass.NumberOfLayers];
System.out.print(Integer.toString(myclass.NumberOfLayers)+">\n");
NodeList nodeStructureContent = nodeStructure.getChildNodes();
for (int isc=0; isc<nodeStructureContent.getLength();isc++)
{
Node nodeLayer = nodeStructureContent.item(isc);
if (nodeLayer.getNodeName().equals("layer"))
{
int index = Integer.parseInt(((Element)nodeLayer).getAttribute("index"));
System.out.print("<layer index = "+Integer.toString(index)+" numberOfNeurons = ");
int number_of_N = Integer.parseInt(((Element)nodeLayer).getAttribute("numberOfNeurons"));
System.out.print(Integer.toString(number_of_N)+">\n");
if(index==0)
{
myclass.Layer[0]=new LAYER(number_of_N,800);
}
else
{
int j=index-1;
myclass.Layer[index]=new LAYER(number_of_N,myclass.Layer[j].Node.length);
}
NodeList nodeLayerContent = nodeLayer.getChildNodes();
for (int ilc=0; ilc<nodeLayerContent.getLength();ilc++)
{
Node nodeNeuron = nodeLayerContent.item(ilc);
if (nodeNeuron.getNodeName().equals("neuron"))
{
System.out.print("<neuron index = ");
int neuron_index = Integer.parseInt(((Element)nodeNeuron).getAttribute("index"));
myclass.Layer[index].Node[neuron_index].Threshold = Double.parseDouble(((Element)nodeNeuron).getAttribute("threshold"));
System.out.print(Integer.toString(neuron_index)+" threshold = "+Double.toString(myclass.Layer[index].Node[neuron_index].Threshold)+">\n");
NodeList nodeNeuronContent = nodeNeuron.getChildNodes();
for (int inc=0; inc < nodeNeuronContent.getLength();inc++)
{
Node nodeNeuralInput = nodeNeuronContent.item(inc);
if (nodeNeuralInput.getNodeName().equals("input"))
{
System.out.print("<input index = ");
int index_input = Integer.parseInt(((Element)nodeNeuralInput).getAttribute("index"));
myclass.Layer[index].Node[neuron_index].Weight[index_input] = Double.parseDouble(((Element)nodeNeuralInput).getAttribute("weight"));
System.out.print(Integer.toString(index_input)+" weight = "+Double.toString(myclass.Layer[index].Node[neuron_index].Weight[index_input])+">\n");
}
}
}
}
}
}
System.out.print("</structure");
}
}
return myclass;
}

Missing Format Argument Exception

When compiling I get a "java.util.MissingFormatArgumentException: null (in java.util.Formater) I do not know why.
"Exception in thread "main" java.util.MissingFormatArgumentException: Format specifier 's'"
Please Help.
import java.lang.*;
import java.util.Random;
import java.util.Scanner;
import static java.lang.System.out;
public class DartSimV1
{
static double[] SiXX(int Money)
{
double[] VarXX;
VarXX = new double[Money];
int IBS;
IBS = 0;
if (IBS < VarXX.length) {
do {
VarXX[IBS] = Math.random();
IBS++;
} while (IBS < VarXX.length);
}
return VarXX;
}
public static double[] SiYY(int Money)
{
double[] VarYY;
VarYY = new double[Money];
int IBS;
IBS = 0;
while (true) {
if (false) {
break;
}
if (!(IBS < VarYY.length)) {
break;
}
VarYY[IBS]=Math.random();
IBS++;
}
return VarYY;
}
public static double WhatPie(double[] IBS,double[] YYCoord)
{
double [] VarXX;
VarXX = IBS;
double [] VarYY;
VarYY = YYCoord;
double Totals;
Totals = 0;
double Contacts;
Contacts = 0;
int IBO;
IBO = 0;
if (IBO < VarXX.length) {
if ((Math.pow(VarXX[IBO], 2) + Math.pow(VarYY[IBO], 2)) <= 1) {
Totals++;
Contacts++;
} else Totals++;
IBO++;
if (IBO < VarXX.length) {
do {
if ((Math.pow(VarXX[IBO], 2) + Math.pow(VarYY[IBO], 2)) <= 1) {
Totals++;
Contacts++;
} else {
Totals++;
}
IBO++;
} while (IBO < VarXX.length);
}
}
double PIE;
PIE = 4 *
(Contacts
/
Totals);
return PIE;
}
public static void Answers(int Done, double New)
{
double PIE;
PIE = New;
System.out.printf("Trial [" + Done +"]: PIE = %11.3f%s",PIE);
}
public static void PieA(double[] New, int Done)
{
double[] PIE;
PIE = New;
int trials;
trials = Done;
double Totals;
Totals = 0.0;
int i;
i = 0;
if (i < PIE.length) {
double IBS;
IBS = PIE[i];
Totals += IBS;
i++;
if (i < PIE.length) {
do {
IBS = PIE[i];
Totals += IBS;
i++;
} while (i < PIE.length);
}
}
double PieA;
PieA = Totals/trials;
System.out.printf("AVG for π = %11.3f%s",PieA);
}
public static void main(String[] args)
{
Scanner show;
show = new Scanner(System.in);
System.out.print("# per trials?: ");
int dPt;
dPt = show.nextInt();
System.out.print("Trial #'s?: ");
int nTri;
nTri = show.nextInt();
double[] PieA;
PieA = new double[nTri];
int IBS=0;
while (IBS<nTri) {
double [] VarXX;
VarXX = SiXX(dPt);
double [] VarYY;
VarYY = SiYY(dPt);
double PIE;
PIE = WhatPie(VarXX,VarYY);
PieA[IBS]=PIE;
Answers(IBS,PIE);
IBS++;
}
PieA(PieA,nTri);
}
}
System.out.printf("Trial [" + Done +"]: PIE = %11.3f%s",PIE); has 2 parameters: one float %11.3f and one string %s. You've only given it one value to print PIE. It needs two - a float and a string.
Also: The exception gives you the full details of the problem - including the line number. You should include that in your question to give people the best chance of answering.

Need Help intrepretting the results of this program

So, I made a small program to test Multithreading in java and compare the time it takes to scale an array using a while loop and then creating multiple threads and running those threads. I'm unsure about then numbers I'm getting when the program finishes, so I was wondering if I made a boneheaded error at some point and messed something up to get very disparate numbers.
Code below:
import java.util.Scanner;
public class arrayScaling {
public static void main(String[] args) throws InterruptedException {
Scanner input = new Scanner(System.in);
System.out.println("Enter the amount of number you want the program to generate:");
int numOfNumbs = input.nextInt();
int [] arrayForNumbers = new int [numOfNumbs];
int [] newArrayForNumbers = new int [numOfNumbs];
for (int i = 0; i < arrayForNumbers.length; i++) {
arrayForNumbers[i] = (int) ((Math.random() * 25) + 1);
}
long startTime = System.nanoTime();
for (int i = 0; i < arrayForNumbers.length; i++) {
newArrayForNumbers[i] = newArrayForNumbers[i] * 3;
}
long endTime = System.nanoTime();
System.out.println();
long totalExecutionTime = endTime-startTime;
System.out.println("Time it takes execute scaling is " +
totalExecutionTime + " nanoseconds");
System.out.println();
int numOfNumLeftOver = numOfNumbs % 5;
int numOfNumDivided = numOfNumbs / 5;
int [] temp = null;
int [] temp2 = null;
int [] temp3 = null;
int [] temp4 = null;
int [] temp5 = null;
MyThread thread1 = new MyThread (numOfNumbs/5);
MyThread thread2 = new MyThread (numOfNumbs/5);
MyThread thread3 = new MyThread (numOfNumbs/5);
MyThread thread4 = new MyThread (numOfNumbs/5);
MyThread thread5;
if (numOfNumLeftOver != 0) {
numOfNumDivided = numOfNumDivided + numOfNumLeftOver;
thread5 = new MyThread (numOfNumDivided);
}
else {
thread5 = new MyThread (numOfNumbs/5);
}
int tempNum = 0;
for ( int i = 0; i < thread1.getArray().length; i ++) {
temp = thread1.getArray();
temp[tempNum] = arrayForNumbers[tempNum];
tempNum++;
}
for ( int i = 0; i < thread2.getArray().length; i ++) {
temp2 = thread2.getArray();
temp2[i] = arrayForNumbers[tempNum];
tempNum++;
}
for ( int i = 0; i < thread3.getArray().length; i ++) {
temp3 = thread3.getArray();
temp3[i] = arrayForNumbers[tempNum];
tempNum++;
}
for ( int i = 0; i < thread4.getArray().length; i ++) {
temp4 = thread4.getArray();
temp4[i] = arrayForNumbers[tempNum];
tempNum++;
}
for ( int i = 0; i < thread5.getArray().length; i ++) {
temp5 = thread5.getArray();
temp5[i] = arrayForNumbers[tempNum];
tempNum++;
}
thread1.setArray(temp);
thread2.setArray(temp2);
thread3.setArray(temp3);
thread4.setArray(temp4);
thread5.setArray(temp5);
long startTime2 = System.nanoTime();
thread1.start();
thread2.start();
thread3.start();
thread4.start();
thread5.start();
thread1.join();
thread2.join();
thread3.join();
thread4.join();
thread5.join();
long endTime2 = System.nanoTime();
long newTotalExecutionTime = endTime2 - startTime2;
System.out.println("Time it takes execute scaling w/ multiple threads is " +
newTotalExecutionTime + " nanoseconds");
if (newTotalExecutionTime < totalExecutionTime) {
System.out.println("Multithreading was more effective");
}
else if (totalExecutionTime < newTotalExecutionTime) {
System.out.println("The original algorithm was more effective");
}
else if (totalExecutionTime == newTotalExecutionTime) {
System.out.println("Both method worked at the same speed");
}
input.close();
}
}
public class MyThread extends Thread {
private int [] array;
private int [] scaleArray;
public MyThread(int size) {
array = new int [size];
scaleArray = new int [size];
}
public int[] getArray() {
return array;
}
public void setArray(int[] array) {
this.array = array;
}
public int[] getScaleArray() {
return scaleArray;
}
public void setScaleArray(int[] scaleArray) {
this.scaleArray = scaleArray;
}
public void run () {
for (int z = 0; z < array.length; z++){
scaleArray[z] = 3 * array[z];
}
}
}
And the output of this program is:
Enter the amount of number you want the program to generate:
16
Time it takes execute scaling is 893 nanoseconds
Time it takes execute scaling w/ multiple threads is 590345 nanoseconds
The original algorithm was more effective
Your results don't surprise me in the slightest. There's a lot of overhead to creating threads, starting them, waiting for them to finish and so on. Don't forget, 590345ns is still less than a millisecond; but most of that is to do with shuffling threads, not with multiplying the numbers.
If you want to see the threaded part of the program outperform the other part, try generating a whole lot more than 16 numbers.

Method Not Displaying Properly

The method "aboveAverage" in the following code is not displaying correctly and I've tried everything I can. Could someone please explain what's going wrong?
My code:
import java.util.*;
public class DailyCatch
{
private int fishermanID, fisherID;
private String dateOfSample, date;
private double[] fishCaught = new double[10];
private int currWeight = 0;
private String summary;
private double average;
private int aboveAvg;
public DailyCatch() { }
public DailyCatch (int fishermanID, String dateOfSample)
{
fisherID = fishermanID;
date = dateOfSample;
}
public DailyCatch (int fishermanID, String dateOfSample, String weight)
{
this(fishermanID, dateOfSample);
readWeights(weight);
}
public void addFish(double weight)
{
if (currWeight > 10)
{
// array full
}
else
{
fishCaught[currWeight] = weight;
currWeight += 1; // update current index of array
}
}
private void readWeights(String weightsAsString)
{
String[] weightsRead = weightsAsString.split("\\s+");
for (int i = 0; i < weightsRead.length; i++)
{
this.addFish(Double.parseDouble(weightsRead[i]));
}
}
public String toString()
{
return "Fisherman ID: " + fisherID + "\nDate:" + date + "\nFish Caught with Weights: " + Arrays.toString(fishCaught);
}
public void printWeights()
{
for (int i = 0; i < fishCaught.length; i++)
{
System.out.println(fishCaught[i]);
}
}
public double averageWeight()
{
double sum = 0;
double count = 0;
for (int i = 0; i < fishCaught.length; i++)
{
if (fishCaught[i] != 0)
{
sum += fishCaught[i];
count += 1;
average = sum/count;
}
}
return average;
}
public String getSummary()
{ int storyTellerCount = 0;
int keeperCount = 0;
int throwBackCount = 0;
for (int i = 0; i < fishCaught.length; i++)
{
if (fishCaught[i] > 5)
{
storyTellerCount++;
}
else if (fishCaught[i] >=1 && fishCaught[i] <= 5)
{
keeperCount++;
}
else if (fishCaught[i] < 1 && fishCaught[i] > 0)
{
throwBackCount++;
}
} String summary = ("\nStoryteller - " + storyTellerCount+ "\nKeeper - " + keeperCount + "\nThrowback - " + throwBackCount);
return summary;
}
public int aboveAverage()
{
int greatAvgCount = 0;
for (int i = 0; i < fishCaught.length; i++)
{
if (fishCaught[i] > average)
{
aboveAvg = greatAvgCount++;
}
}
return aboveAvg;
}
}
Test Code:
public class BigBass
{
public static void main (String[]args)
{
//Part 1
DailyCatch monday1 = new DailyCatch(32, "4/1/2013", "4.1 5.5 2.3 0.5 4.8 1.5");
System.out.println(monday1);
//Part 2
DailyCatch monday2 = new DailyCatch(44, "4/1/2013");
System.out.println(monday2);
monday2.addFish(2.1);
monday2.addFish(4.2);
System.out.println(monday2);
//Part 3
System.out.println("\n\nSUMMARY OF FISHERMAN 32");
System.out.println(monday1.getSummary());
//Part 4
double avg = monday1.averageWeight();
System.out.printf("\nThere are %d fish above the average weight of %.1f.", monday1.aboveAverage(), avg);
}
}
I just need to get Part 4 to work here. What it does is return that there have been 2 fish caught that are above average when I know it should be 3. The average is 3.1.
A simple mistake.
public int aboveAverage() {
int greatAvgCount = 0;
for (int i = 0; i < fishCaught.length; i++) {
if (fishCaught[i] > 3.1) {
greatAvgCount++; // no 'return'
}
}
return greatAvgCount;
}
if (fishCaught[i] > 3.1)
{
return greatAvgCount++;
}
First try : 4.1 > 3.1
true
returns 0 ++ which is 0 basically
You can increment the counter inside the loop and keep the return statement for the end only.
try
public int aboveAverage() {
int greatAvgCount = 0;
for (int i = 0; i < fishCaught.length; i++) {
if (fishCaught[i] > 3.1) {
greatAvgCount++;
}
}
return greatAvgCount;
}
This line is your problem,
return greatAvgCount++;
you are incrimenting greatAvgCount then returning its initial value, there should be no "return" on this line
The aboveAverage method should be
public int aboveAverage()
{
int greatAvgCount = 0;
for (int i = 0; i < fishCaught.length; i++)
{
if (fishCaught[i] > 3.1)
{
greatAvgCount++;
}
}
return greatAvgCount;
}
Also, you may just be doing it for debug, in which case fair enough, but hardcoding the "average" as 3.1 is generally considered bad practice. If you want average to be always 3.1 (i.e. its a global average that you've looked up from a book then its more usual to declare a static variable called double AVERAGE=3.1 and then use that where ever average is required, that way if the "book value" changes you only need to change average in one place in your code. If average is calculated from your data obviously you should use the calculated value.
Also not directly related to your problem but why are you using an array for your caught fish with a predefined maximum of 10. If you used an ArrayList you could add to it as you saw fit and it would auto expand to accommodate
private double[] fishCaught = new double[10];
becomes
private ArrayList<Double> fishCaught = new ArrayList<Double>();

Categories