Would anyone be able to tell me what is wrong with this code where I have attempted to implement 4 threads into a Mandelbrot program. The first half of the image in the file is not rendering. Thanks!
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Week2;
/**
*
* #author Alex Humphris
*/
import java.awt.Color;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import java.io.File;
public class ParallelMandelbrot4 extends Thread {
final static int N = 4096;
final static int CUTOFF = 100;
static int[][] set = new int[N][N];
public static void main(String[] args) throws Exception {
// Calculate set
long startTime = System.currentTimeMillis();
ParallelMandelbrot4 thread0 = new ParallelMandelbrot4(0);
ParallelMandelbrot4 thread1 = new ParallelMandelbrot4(1);
ParallelMandelbrot4 thread2 = new ParallelMandelbrot4(2);
ParallelMandelbrot4 thread3 = new ParallelMandelbrot4(3);
thread0.start();
thread1.start();
thread2.start();
thread3.start();
thread0.join();
thread1.join();
thread2.join();
thread3.join();
long endTime = System.currentTimeMillis();
System.out.println("Calculation completed in "
+ (endTime - startTime) + " milliseconds");
// Plot image
BufferedImage img = new BufferedImage(N, N,
BufferedImage.TYPE_INT_ARGB);
// Draw pixels
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
int k = set[i][j];
float level;
if (k < CUTOFF) {
level = (float) k / CUTOFF;
} else {
level = 0;
}
Color c = new Color(0, level, 0); // Green
img.setRGB(i, j, c.getRGB());
}
}
// Print file
ImageIO.write(img, "PNG", new File("Mandelbrot.png"));
}
int me;
public ParallelMandelbrot4(int me) {
this.me = me;
}
public void run() {
int begin, end;
if (me == 0) {
begin = 0;
end = (N / 4) * 1;
}
if (me == 1) {
begin = (N / 4) * 1;
end = (N / 4) * 2;
}
if (me == 2) {
begin = (N / 4) * 2;
end = (N / 4) * 3;
} else { // me == 1
begin = (N / 4) * 3;
end = N;
}
for (int i = begin; i < end; i++) {
for (int j = 0; j < N; j++) {
double cr = (4.0 * i - 2 * N) / N;
double ci = (4.0 * j - 2 * N) / N;
double zr = cr, zi = ci;
int k = 0;
while (k < CUTOFF && zr * zr + zi * zi < 4.0) {
// z = c + z * z
double newr = cr + zr * zr - zi * zi;
double newi = ci + 2 * zr * zi;
zr = newr;
zi = newi;
k++;
}
set[i][j] = k;
}
}
}
}
There error lies in your run() statement. By adding the if statement for (me == 3), the entire image is rendered, whereas before, the else statement at the end was being called in 3 different threads.
This is because of the else at the end of your code. Say for example me is 1. When it is one, it will execute the code in the if (me == 1) statement, and it will also execute the code at the end, as me is not equal to 2.
To fix this, I would recommend using the if else statements:
int begin = 0, end = 0;
if (me == 0) {
begin = 0;
end = (N / 4) * 1;
}
else if (me == 1) {
begin = (N / 4) * 1;
end = (N / 4) * 2;
}
else if (me == 2) {
begin = (N / 4) * 2;
end = (N / 4) * 3;
}
else if (me == 3) {
begin = (N / 4) * 3;
end = N;
}
The multithreading part is almost correct. It's the constructor that had some issues. You should consider making me a final private variable. #Skepter's answer is correct. This is how it looks in my IDE and that gave me an idea with the funkiness of the if-else you are using.
Fixing it thus should work:
private final int me;
public ParallelMandelbrot4(int me) {
this.me = me;
}
public void run() {
int begin, end;
if (me == 0) {
begin = 0;
end = (N / 4) * 1;
}
else if (me == 1) {
begin = (N / 4) * 1;
end = (N / 4) * 2;
}
else if (me == 2) {
begin = (N / 4) * 2;
end = (N / 4) * 3;
} else { // me == 3
begin = (N / 4) * 3;
end = N;
}
Related
In my Pulse Wave generator, I need to find the value of cyclePoint (c) from cycleFrequency (f), cycleRange (r), minDutyCycle (m) and dutyCycle d.
Here is a formula that I made that finds the value of dutyCycle (d) from the other value
D = ((c/(f/2))r)+m
I'm not the best at algebra so I probably used the brackets wrong.
Here is my code
public class PulseGenerator extends SquareGenerator {
// constants
public static final double DEF_MIN_DUTY_CYCLE = 0.05;
public static final double DEF_MAX_DUTY_CYCLE = 0.95;
public static final double DEF_CYCLE_FREQ = 2;
public static final double DEF_HOLD_CYCLE = 0;
// instance variables
double minDutyCycle;
double maxDutyCycle;
double cycleFreq;
double holdCycle;
double dutyCycleRange;
boolean setDirection;
// constructor
public PulseGenerator(double amplitude, double frequency, int bitRate,
double duration, double dutyCycle, double minDutyCycle,
double maxDutyCycle, double cycleFreq, double holdCycle) {
super(amplitude, frequency, bitRate, duration, dutyCycle);
// sample data
squareSample = new int[sampleLength];
calculateAmpLimit();
this.dutyCycle = dutyCycle;
waveLength = sampleRate / this.frequency;
this.minDutyCycle = minDutyCycle;
this.maxDutyCycle = maxDutyCycle;
this.cycleFreq = cycleFreq * sampleRate;
this.holdCycle = holdCycle * sampleRate;
dutyCycleRange = this.maxDutyCycle - this.minDutyCycle;
setDirection = false;
}
// one arg cunstructor
public PulseGenerator(double frequency) {
this(AMPLITUDE, frequency, BIT_RATE, DURATION, DEF_DUTY_CYCLE,
DEF_MIN_DUTY_CYCLE, DEF_MAX_DUTY_CYCLE, DEF_CYCLE_FREQ,
DEF_HOLD_CYCLE);
}
// no args constructor
public PulseGenerator() {
this(AMPLITUDE, FREQUENCY, BIT_RATE, DURATION, DEF_DUTY_CYCLE,
DEF_MIN_DUTY_CYCLE, DEF_MAX_DUTY_CYCLE, DEF_CYCLE_FREQ,
DEF_HOLD_CYCLE);
}
// generate waveform method
#Override
public int[] generateWaveForm() {
// define the decimal j
double j = 1;
// define cycle point
// here is where I need to find the value of cycle point
int cyclePoint = (int)((dutyCycle * (cycleFreq / 2) - minDutyCycle) / dutyCycleRange);
System.out.println("Cycle point: " + cyclePoint);
// generate the actual waveform
for (int i = 0; i < sampleLength; i++, j++) {
double waveCycleRatio = waveLength * dutyCycle;
// same as square
// draws the wave
if (j - waveCycleRatio < 0.0) {
finePoint = 1.0;
} else if (j - waveCycleRatio >= 0.0
&& j - waveCycleRatio < 1) {
finePoint = 0 - (j - waveCycleRatio - 0.5) * 2;
} else if (j - waveLength < 0.0) {
finePoint = -1.0;
} else if (j - waveLength >= 0.0) {
finePoint = (j - waveLength - 0.5) * 2;
}
// checks if j is equal to wavelength
if (j == waveLength) {
j = 1;
} else if (j - waveLength > 0.0 && j - waveLength < 1.0) {
j = (j - waveLength);
}
point = (int)(finePoint * ampLimit);
squareSample[i] = point;
if (holdCycle > 0) {
holdCycle--;
} else {
// implementation of formula to find duty cycle
dutyCycle = (cyclePoint / (cycleFreq / 2) * dutyCycleRange)
+ minDutyCycle;
if (cyclePoint < cycleFreq / 2 && !setDirection) {
cyclePoint++;
} else if (cyclePoint >= cycleFreq / 2 && !setDirection) {
cyclePoint--;
setDirection = true;
} else if (cyclePoint > 0 && setDirection) {
cyclePoint--;
} else if (cyclePoint <= 0 && setDirection) {
cyclePoint++;
setDirection = false;
}
}
}
// return the sample data
return squareSample;
}
}
I believe this line is a bit off:
int cyclePoint = (int)((dutyCycle * (cycleFreq / 2) - minDutyCycle) / dutyCycleRange);
and it should be like:
int cyclePoint = (int)((cycleFreq / 2) * (dutyCycle - minDutyCycle) / dutyCycleRange);
This code line:
int cyclePoint = (int)((dutyCycle * (cycleFreq / 2) - minDutyCycle) / dutyCycleRange);
should be replaced with:
int cyclePoint = (int) (((dutyCycle - minDutyCycle) * cycleFreq) / (2 * dutyCycleRange));
I am building a pulse wave generator that extends a square wave generator.
My problem is I want the pulse width modulation transition to be smoother
I am trying to make the middle sample between the peak and trough of the wave to move smoothly up or down while the width is modulated.
This is so higher sounds such as C7 at 2093 Hz don't sound clicky as the duty cycle is modulated.
What needs to be done?
Sample rate is 44100
Bit rate is 16
ampLimit is the highest possible value.
duration is the length of waveform in seconds
duty cycle is the starting cycle of the waveform
public class PulseGenerator extends SquareGenerator {
// constants
public static final double DEF_MIN_DUTY_CYCLE = 0.05;
public static final double DEF_MAX_DUTY_CYCLE = 0.95;
public static final double DEF_CYCLE_FREQ = 2;
public static final double DEF_HOLD_CYCLE = 0;
// instance variables
double minDutyCycle; // minimum value of duty cycle
double maxDutyCycle; // maximum value of duty cycle
double cycleFreq;
double holdCycle; // if more than zero, the wave will hold the modulation for that period
double dutyCycleRange; // maxDutyCycle - minDutyCycle
boolean setDirection;
// constructor
public PulseGenerator(double amplitude, double frequency, int bitRate,
double duration, double dutyCycle, double minDutyCycle,
double maxDutyCycle, double cycleFreq, double holdCycle) {
super(amplitude, frequency, bitRate, duration, dutyCycle);
// sample data
squareSample = new int[sampleLength];
calculateAmpLimit();
this.dutyCycle = dutyCycle;
waveLength = SAMPLE_RATE / this.frequency;
this.minDutyCycle = minDutyCycle;
this.maxDutyCycle = maxDutyCycle;
this.cycleFreq = cycleFreq * SAMPLE_RATE;
this.holdCycle = holdCycle * SAMPLE_RATE;
dutyCycleRange = this.maxDutyCycle - this.minDutyCycle;
setDirection = false;
}
// one arg cunstructor
public PulseGenerator(double frequency) {
this(AMPLITUDE, frequency, BIT_RATE, DURATION, DEF_DUTY_CYCLE,
DEF_MIN_DUTY_CYCLE, DEF_MAX_DUTY_CYCLE, DEF_CYCLE_FREQ,
DEF_HOLD_CYCLE);
}
// no args constructor
public PulseGenerator() {
this(AMPLITUDE, FREQUENCY, BIT_RATE, DURATION, DEF_DUTY_CYCLE,
DEF_MIN_DUTY_CYCLE, DEF_MAX_DUTY_CYCLE, DEF_CYCLE_FREQ,
DEF_HOLD_CYCLE);
}
// generate waveform method
#Override
public int[] generateWaveForm() {
// define cycle point
int cyclePoint = (int)(cycleFreq / 2 * ((dutyCycle * dutyCycleRange) + minDutyCycle));
// generate the actual waveform
for (int i = 0, j = 0; i < sampleLength; i++, j++) {
double waveCycleRatio = waveLength * dutyCycle;
// same as square generate method
if (j - waveCycleRatio < 0.0) {
finePoint = 1.0;
} else if (j - waveCycleRatio >= 0.0
&& j - waveCycleRatio < 1) {
finePoint = 1 - (j - waveCycleRatio);
} else if (j - waveLength < 0.0) {
finePoint = -1.0;
} else if (j - waveLength >= 0.0) {
finePoint = -1 + (waveLength - j);
}
if (j >= waveLength) {
j = 1;
}
point = (int)finePoint * ampLimit;
squareSample[i] = point;
if (holdCycle > 0) {
holdCycle--;
} else {
dutyCycle = (cyclePoint / (cycleFreq / 2) * dutyCycleRange)
+ minDutyCycle;
if (cyclePoint < cycleFreq / 2 && !setDirection) {
cyclePoint++;
} else if (cyclePoint >= cycleFreq / 2 && !setDirection) {
cyclePoint--;
setDirection = true;
} else if (cyclePoint > 0 && setDirection) {
cyclePoint--;
} else if (cyclePoint <= 0 && setDirection) {
cyclePoint++;
setDirection = false;
}
}
}
// return the sample data
return squareSample;
}
}
I actually found out what was wrong, first I was converting the fine point to an int before I multiplied it by the amp limit. second the code for the fine point needed to be repositioned and multiplied by two.
// generate the actual waveform
for (int i = 0, j = 0; i < sampleLength; i++, j++) {
double waveCycleRatio = waveLength * dutyCycle;
// same as square
if (j - waveCycleRatio < 0.0) {
finePoint = 1.0;
} else if (j - waveCycleRatio >= 0.0
&& j - waveCycleRatio < 1) {
finePoint = 0 - (j - waveCycleRatio - 0.5) * 2;
} else if (j - waveLength < 0.0) {
finePoint = -1.0;
} else if (j - waveLength >= 0.0) {
finePoint = (j - waveLength - 0.5) * 2;
}
if (j >= waveLength) {
j = 1;
}
point = (int)(finePoint * ampLimit);
squareSample[i] = point;
if (holdCycle > 0) {
holdCycle--;
} else {
dutyCycle = (cyclePoint / (cycleFreq / 2) * dutyCycleRange)
+ minDutyCycle;
if (cyclePoint < cycleFreq / 2 && !setDirection) {
cyclePoint++;
} else if (cyclePoint >= cycleFreq / 2 && !setDirection) {
cyclePoint--;
setDirection = true;
} else if (cyclePoint > 0 && setDirection) {
cyclePoint--;
} else if (cyclePoint <= 0 && setDirection) {
cyclePoint++;
setDirection = false;
}
}
}
I'm doing an article right now about code I wrote. I'm calculating values that go past the limit of the variable long and I also need to compare this values, so I'm using BigInteger instead.
The thing is, BigInteger is immutable so every time a new calculation happen, my program runs slower and slower cause a new BigInteger is being added in an array or something.
After some research I learned about MutableBigInteger and tried to use it, but I can't import this class because its private from java.util.Math. I found a topic where some one was using MutableBigInteger Performance of MutableBigInteger
The problem is, I couldn't understand much of his code, thus I don't know how to use an mutable version of BigInteger. I read a little about BitSet as well but I don't think it would help me in this scenario.
Imagine a clock with n numbers >0. You need to "cut" this clock in 2 (imagine a clock with 15 numbers, I'll put a risk in the number 1 and another on the number 7) now I need to check if the sum of numbers between 1 and 7 are equal to the sum between 7 and 1 (7 till n then this result 'till cut 1)
Here's my code:
public class LinePuzzle {
private static int tam;
private static int cont = 0;
private static int t1parte, t2parte, t3parte, t4parte, ajuda, ajuda2;
static int geraCortes(int tam) {
Thread tt1 = new Thread(t1);
Thread tt2 = new Thread(t2);
Thread tt3 = new Thread(t3);
Thread tt4 = new Thread(t4);
if(tam % 2 == 0){
ajuda = tam/4;
t1parte = ajuda;
t2parte = ajuda*2;
t3parte = ajuda*3;
t4parte = ajuda*4;
}else{
ajuda2 = tam%4;
ajuda = (tam-ajuda2)/4;
t1parte = ajuda;
t2parte = (ajuda*2);
t3parte = (ajuda*3);
t4parte = (ajuda*4) + ajuda2;
}
// "Starts"
tt1.start();
tt2.start();
tt3.start();
tt4.start();
try {
//
tt1.join();
tt2.join();
tt3.join();
tt4.join();
} catch (Exception ex) {
System.out.println("Finalizado");
}
return cont;
}
private static Runnable t1 = new Runnable() {
#Override
public void run() {
long soma1, soma2;
for (int i = 0; i<= t1parte; i++) { // 1º cut
for (int j = i + 1; j <= tam; j++) { // 2º cut
if (i == j || i == j - 1) { // tests
continue;
}
soma1 = (((i + 1) + (j - 1)) * (j - i - 1)) / 2;
soma2 = (((j + 1) + tam) * (tam - j) + (1 + (i - 1)) * (i - 1)) / 2;
if (soma1 == soma2 && soma1 != 0) {
BigInteger bi, bi2;
bi = BigInteger.valueOf(soma1);
bi2 = BigInteger.valueOf(soma2);
if(bi.equals(bi2)){
System.out.printf("Equals: cut1 = %d and cut2 = %d -> result: %s / %s\n", i, j, bi, bi2);
cont++;
break;
}
}
}
}
}
};
private static Runnable t2 = new Runnable() {
#Override
public void run() {
long soma1, soma2;
for (int i = t1parte; i<= t2parte; i++) {
for (int j = i + 1; j <= tam; j++) {
if (i == j || i == j - 1) {
continue;
}
soma1 = (((i + 1) + (j - 1)) * (j - i - 1)) / 2;
soma2 = (((j + 1) + tam) * (tam - j) + (1 + (i - 1)) * (i - 1)) / 2;
if (soma1 == soma2 && soma1 != 0) {
BigInteger bi, bi2;
bi = BigInteger.valueOf(soma1);
bi2 = BigInteger.valueOf(soma2);
if(bi.equals(bi2)){
System.out.printf("Equals: cut1 = %d and cut2 = %d -> result: %s / %s\n", i, j, bi, bi2);
cont++;
break;
}
}
}
}
}
};
private static Runnable t3 = new Runnable() {
#Override
public void run() {
long soma1, soma2;
for (int i = t2parte; i<= t3parte; i++) { // 1º corte
for (int j = i + 1; j <= tam; j++) { // 2º corte
if (i == j || i == j - 1) {
continue;
}
soma1 = (((i + 1) + (j - 1)) * (j - i - 1)) / 2;
soma2 = (((j + 1) + tam) * (tam - j) + (1 + (i - 1)) * (i - 1)) / 2;
if (soma1 == soma2 && soma1 != 0) {
BigInteger bi, bi2;
bi = BigInteger.valueOf(soma1);
bi2 = BigInteger.valueOf(soma2);
if(bi.equals(bi2)){
System.out.printf("Equals: cut1 = %d and cut2 = %d -> result: %s / %s\n", i, j, bi, bi2);
cont++;
break;
}
}
}
}
}
};
private static Runnable t4 = new Runnable() {
#Override
public void run() {
long soma1, soma2;
for (int i = t3parte; i<= t4parte; i++) { // 1º corte
for (int j = i + 1; j <= tam; j++) { // 2º corte
if (i == j || i == j - 1) {
continue;
}
soma1 = (((i + 1) + (j - 1)) * (j - i - 1)) / 2;
soma2 = (((j + 1) + tam) * (tam - j) + (1 + (i - 1)) * (i - 1)) / 2;
if (soma1 == soma2 && soma1 != 0) {
BigInteger bi, bi2;
bi = BigInteger.valueOf(soma1);
bi2 = BigInteger.valueOf(soma2);
if(bi.equals(bi2)){
System.out.printf("Equals: cut1 = %d and cut2 = %d -> result: %s / %s\n", i, j, bi, bi2);
cont++;
break;
}
}
}
}
}
};
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
do{
System.out.println("Clock length: ");
tam = scan.nextInt();
}while(tam < 2);
System.out.println("Numbers of equals: " + geraCortes(tam)); // executar o geracortes e os threads
}
}
You need to understand how to use BigInteger to make calculations.
Below are examples with two of your calculations (assuming i, j, tam are longs):
//(((i + 1) + (j - 1)) * (j - i - 1)) / 2;
BigInteger bSoma1 = bigI.add(BigInteger.ONE)
.add(bigJ.subtract(BigInteger.ONE))
.multiply(bigJ.subtract(bigI).subtract(BigInteger.ONE))
.divide(BigInteger.valueOf(2));
//(((j + 1) + tam) * (tam - j) + (1 + (i - 1)) * (i - 1)) / 2;
BigInteger bSoma2 = bigJ.add(BigInteger.ONE).add(bigTam)
.multiply(bigTam.subtract(bigJ))
.add(BigInteger.ONE.add(bigI.subtract(BigInteger.ONE)))
.multiply(bigI.subtract(BigInteger.ONE))
.divide(BigInteger.valueOf(2));
I'm trying to do the Algorithm programming assignment of Princeton , and I met a problem about the memory test. The assignment requires us run the percolation program N times and find the medium of the result, and I write a percolationtest.java and for each time, I create an instance variable, it worked, but use too much memory, and the instructor suggests me to use local variable, but I don't know how. Can some one help me and give me some advice, I really appreciate it.
public class PercolationStats {
private int N, T, totalSum;
private double []fraction;
private int []count;
public PercolationStats(int N, int T) {
if (N <= 0 || T <= 0)
throw new IllegalArgumentException();
else {
this.N = N;
this.T = T;
count = new int [T];
totalSum = N*N;
fraction = new double[T];
int randomX, randomY;
for (int i = 0; i < T; i++) {
Percolation perc = new Percolation(N);
while (true) {
if (perc.percolates()) {
fraction[i] = (double) count[i]/totalSum;
break;
}
randomX = StdRandom.uniform(1, N+1);
randomY = StdRandom.uniform(1, N+1);
if (perc.isOpen(randomX, randomY)) continue;
else {
perc.open(randomX, randomY);
count[i]++;
}
}
}
}
} // perform T independent experiments on an N-by-N grid
public double mean() {
double totalFraction = 0;
for (int i = 0; i < T; i++) {
totalFraction += fraction[i];
}
return totalFraction/T;
} // sample mean of percolation threshold
public double stddev() {
double u = this.mean();
double sum = 0;
for (int i = 0; i < T; i++) {
sum += (fraction[i] - u) * (fraction[i] - u);
}
return Math.sqrt(sum/(T-1));
} // sample standard deviation of percolation threshold
public double confidenceLo() {
double u = this.mean();
double theta = this.stddev();
double sqrtT = Math.sqrt(T);
return u-1.96*theta/sqrtT;
} // low endpoint of 95% confidence interval
public double confidenceHi() {
double u = this.mean();
double theta = this.stddev();
double sqrtT = Math.sqrt(T);
return u+1.96*theta/sqrtT;
} // high endpoint of 95% confidence interval
public static void main(String[] args) {
int N = 200;
int T = 100;
if (args.length == 1) N = Integer.parseInt(args[0]);
else if (args.length == 2) {
N = Integer.parseInt(args[0]);
T = Integer.parseInt(args[1]); }
PercolationStats a = new PercolationStats(N, T);
System.out.print("mean = ");
System.out.println(a.mean());
System.out.print("stddev = ");
System.out.println(a.stddev());
System.out.print("95% confidence interval = ");
System.out.print(a.confidenceLo());
System.out.print(", ");
System.out.println(a.confidenceHi());
}
}
public class Percolation {
private boolean[][] site;
private WeightedQuickUnionUF uf;
private int N;
public Percolation(int N) {
if (N < 1)
throw new IllegalArgumentException();
else {
site = new boolean[N + 2][N + 2];
for (int j = 1; j <= N; j++) {
site[0][j] = true;
site[N + 1][j] = true;
}
uf = new WeightedQuickUnionUF((N + 2) * (N + 2));
for (int i = 1; i <= N; i++) {
uf.union(0, i);
}
this.N = N;
}
}
public void open(int i, int j) {
if (i > N || i < 1 || j > N || j < 1)
throw new IndexOutOfBoundsException();
else {
if (!site[i][j]) {
site[i][j] = true;
if (site[i - 1][j]) {
uf.union((N + 2) * (i - 1) + j, (N + 2) * i + j);
}
if (site[i + 1][j]) {
uf.union((N + 2) * i + j, (N + 2) * (i + 1) + j);
}
if (site[i][j + 1]) {
uf.union((N + 2) * i + (j + 1), (N + 2) * i + j);
}
if (site[i][j - 1]) {
uf.union((N + 2) * i + (j - 1), (N + 2) * i + j);
}
}
}
}
public boolean isOpen(int i, int j) {
if (i > N || i < 1 || j > N || j < 1)
throw new IndexOutOfBoundsException();
else
return site[i][j];
}
public boolean isFull(int i, int j) {
if (i > N || i < 1 || j > N || j < 1)
throw new IndexOutOfBoundsException();
else
return site[i][j] && (i == 1 || uf.connected((N + 2) * i + j, 0));
}
public boolean percolates() {
for (int i = 1; i <= N; i++) {
if (this.isFull(N, i)) {
return true;
}
}
return false;
}
public static void main(String[] args) {
}
}
Added meanValue instance variable to keep mean value and replaced it in multiple places where you used to call mean() method which was over head to calculate again and again. Also modified "int[] count" as local variable which you were not using outside the constructor. post your "Percolation" and "StdRandom" classes for more optimization of code. you can run this code and test, it should reduce the runtime than yours.
public class PercolationStats {
private int N, T, totalSum;
private double []fraction;
private double meanValue;
public PercolationStats(int N, int T) {
if (N <= 0 || T <= 0)
throw new IllegalArgumentException();
else {
this.N = N;
this.T = T;
int [] count = new int [T];
totalSum = N*N;
fraction = new double[T];
int randomX, randomY;
for (int i = 0; i < T; i++) {
Percolation perc = new Percolation(N);
while (true) {
if (perc.percolates()) {
fraction[i] = (double) count[i]/totalSum;
break;
}
randomX = StdRandom.uniform(1, N+1);
randomY = StdRandom.uniform(1, N+1);
if (perc.isOpen(randomX, randomY)) continue;
else {
perc.open(randomX, randomY);
count[i]++;
}
}
}
}
}
// perform T independent experiments on an N-by-N grid
public double mean() {
double totalFraction = 0;
for (int i = 0; i < T; i++) {
totalFraction += fraction[i];
}
meanValue = totalFraction/T;
return meanValue;
} // sample mean of percolation threshold
public double stddev() {
double u = meanValue;
double sum = 0;
for (int i = 0; i < T; i++) {
sum += (fraction[i] - u) * (fraction[i] - u);
}
return Math.sqrt(sum/(T-1));
} // sample standard deviation of percolation threshold
public double confidenceLo() {
double u = meanValue;
double theta = this.stddev();
double sqrtT = Math.sqrt(T);
return u-1.96*theta/sqrtT;
} // low endpoint of 95% confidence interval
public double confidenceHi() {
double u = meanValue;
double theta = this.stddev();
double sqrtT = Math.sqrt(T);
return u+1.96*theta/sqrtT;
} // high endpoint of 95% confidence interval
public static void main(String[] args) {
int N = 200;
int T = 100;
if (args.length == 1) N = Integer.parseInt(args[0]);
else if (args.length == 2) {
N = Integer.parseInt(args[0]);
T = Integer.parseInt(args[1]); }
PercolationStats a = new PercolationStats(N, T);
System.out.print("mean = ");
System.out.println(a.mean());
System.out.print("stddev = ");
System.out.println(a.stddev());
System.out.print("95% confidence interval = ");
System.out.print(a.confidenceLo());
System.out.print(", ");
System.out.println(a.confidenceHi());
}
}
Since some weeks ago I have been trying to convert this c and other c function to java language (i'm a newbie on it).
My first problem is how-to convert to java code, the pointers on lines like:
q = fdata + ind;
datend = fdata + buff_size;
For example when "ind" has a negative position (-220 for example) the pointer will be on "ind" position before "fdata" values, also the same occur with datend var.
I figured out that can be solved on isolated way by creating an index var for each pointer to know where there are pointing at. The real problem for me comes a few line after that, when i trying to not run over end of frame of "fdata" array.
Can some body with more experiences help me please?
Thank.
static Stat *stat = NULL;
static float *mem = NULL;
static Stat*
get_stationarity(fdata, freq, buff_size, nframes, frame_step, first_time)
float *fdata;
double freq;
int buff_size, nframes, frame_step, first_time;
{
static int nframes_old = 0, memsize;
float preemp = 0.4f, stab = 30.0f;
float *p, *q, *r, *datend;
int ind, i, j, m, size, order, agap, w_type = 3;
agap = (int) (STAT_AINT * freq);
size = (int) (STAT_WSIZE * freq);
ind = (agap - size) / 2;
if (nframes_old < nframes || !stat || first_time) {
/* move this to init_dp_f0() later */
nframes_old = nframes;
if (stat) {
ckfree((char *) stat->stat);
ckfree((char *) stat->rms);
ckfree((char *) stat->rms_ratio);
ckfree((char *) stat);
}
if (mem) ckfree((void *) mem);
stat = (Stat *) ckalloc(sizeof (Stat));
stat->stat = (float*) ckalloc(sizeof (float) *nframes);
stat->rms = (float*) ckalloc(sizeof (float) *nframes);
stat->rms_ratio = (float*) ckalloc(sizeof (float) *nframes);
memsize = (int) (STAT_WSIZE * freq) + (int) (STAT_AINT * freq);
mem = (float *) ckalloc(sizeof (float) * memsize);
for (j = 0; j < memsize; j++) mem[j] = 0;
}
if (nframes == 0) return (stat);
q = fdata + ind;
datend = fdata + buff_size;
if ((order = (int) (2.0 + (freq / 1000.0))) > BIGSORD) {
fprintf(stderr,
"exceeds that allowable (%d); reduce Fs\n", BIGSORD);
order = BIGSORD;
}
/* prepare for the first frame */
for (j = memsize / 2, i = 0; j < memsize; j++, i++) mem[j] = fdata[i];
/* do not run over end of frame */
for (j = 0, p = q - agap; j < nframes; j++, p += frame_step, q += frame_step) {
if ((p >= fdata) && (q >= fdata) && (q + size <= datend))
stat->stat[j] = get_similarity(order, size, p, q,
&(stat->rms[j]),
&(stat->rms_ratio[j]), preemp,
stab, w_type, 0);
else {
if (first_time) {
if ((p < fdata) && (q >= fdata) && (q + size <= datend))
stat->stat[j] = get_similarity(order, size, NULL, q,
&(stat->rms[j]),
&(stat->rms_ratio[j]),
preemp, stab, w_type, 1);
else {
stat->rms[j] = 0.0;
stat->stat[j] = 0.01f * 0.2f; /* a big transition */
stat->rms_ratio[j] = 1.0; /* no amplitude change */
}
} else {
if ((p < fdata) && (q + size <= datend)) {
stat->stat[j] = get_similarity(order, size, mem,
mem + (memsize / 2) + ind,
&(stat->rms[j]),
&(stat->rms_ratio[j]),
preemp, stab, w_type, 0);
/* prepare for the next frame_step if needed */
if (p + frame_step < fdata) {
for (m = 0; m < (memsize - frame_step); m++)
mem[m] = mem[m + frame_step];
r = q + size;
for (m = 0; m < frame_step; m++)
mem[memsize - frame_step + m] = *r++;
}
}
}
}
}
/* last frame, prepare for next call */
for (j = (memsize / 2) - 1, p = fdata + (nframes * frame_step) - 1; j >= 0 && p >= fdata; j--)
mem[j] = *p--;
return (stat);
}
This code is easier rewritten than ported. The reason is, that it uses a large number of pointer-arithmetic and casting.
It looks to me like this code combines a sliding window and averaging functions over the data. You can easily do this in Java, just place each time-series in an array, use an index (instead of a pointer) to point at the array's entries. In the case where the C-code uses a pointer and then a (possibly negative) offset as a second pointer just use two indices into the time-series-array.
It is easier to do this if you have the formula (math-notation. sliding-window plus averaging functions) that this code is supposed to compute and translate the formula to java.