I am working on a simple program to calculate a mathematical equation. But there is a problem that I could not find. Any help would be greatly appreciated.
It seems a problem is with
alpha[j] = (double)(j-1)*2*Math.PI/(double)rotationNum;
NullPointerException is returned. There has to be some silly mistakes here.
import java.util.*;
import java.io.*;
//import Jama.Matrix;
class efun {
static double epso;
static double sigma;
static double alpha[];
static double charge;
static double axisR;
static double axisZ;
//static Random randGen;
static int numPoints = -1;
static int rotationNum;
public static void main (String[] args) {
try {
sigma = 300e-6*1e2;
epso = 8.854e-12;
/*Input arguments*/
numPoints = Integer.parseInt (args[0]);
FileReader fr = new FileReader(args[1]);
rotationNum = Integer.parseInt (args[2]);
BufferedReader br = new BufferedReader(fr);
double pointsR[] = new double[numPoints];
double pointsZ[] = new double[numPoints];
double chargeDensity[] = new double[numPoints];
double electricField = 0.0;
double ER = 0.0;
double EZ = 0.0;
double EY = 0.0;
for (int id = 0; id < numPoints; id++) {
// read file
while ( (line = br.readLine() )!= null) {
StringTokenizer stk = new StringTokenizer(line);
axisR = Double.parseDouble(stk.nextToken());
axisZ = Double.parseDouble(stk.nextToken());
charge = Double.parseDouble(stk.nextToken());
pointsR[id] = axisR;
pointsZ[id] = axisZ;
chargeDensity[id] = charge;
System.out.println("axisR: "+pointsR[id]+" and axisZ: "+ pointsZ[id]+"; its corresponding charge density is: "+ chargeDensity[id]);
double rotatedR[] = new double[numPoints];
double rotatedZ[] = new double[numPoints];
double rotatedY[] = new double[numPoints];
double sumSquarePoints[] = new double[numPoints];
for (int j = 1; j < rotationNum+1; j++) {
alpha[j] = (double)(j-1)*2*Math.PI/(double)rotationNum;
System.out.println("print alpha: "+alpha[j]);
rotatedR[id] = pointsR[id] - Math.cos(alpha[j])*pointsR[id];
rotatedZ[id] = pointsZ[id];
rotatedY[id] = pointsR[id] - Math.sin(alpha[j])*pointsR[id];
sumSquarePoints[id] = Math.sqrt(rotatedR[id]*rotatedR[id] + rotatedZ[id]*rotatedZ[id] + rotatedY[id]*rotatedY[id]);
ER += chargeDensity[id]*rotatedR[id]/(sumSquarePoints[id]*sumSquarePoints[id]*sumSquarePoints[id]);
EZ += chargeDensity[id]*rotatedZ[id]/(sumSquarePoints[id]*sumSquarePoints[id]*sumSquarePoints[id]);
EY += chargeDensity[id]*rotatedY[id]/(sumSquarePoints[id]*sumSquarePoints[id]*sumSquarePoints[id]);
System.out.println ("ER is: "+ ER);
System.out.println ("EZ is: "+ EZ);
System.out.println ("EY is: "+ EY);
}
}
}
electricField = sigma/(4*Math.PI*epso)*Math.sqrt(ER*ER + EZ*EZ + EY*EY);
System.out.println("electricField is: " + electricField);
}
catch (Exception e) {
e.printStackTrace();
}
}
}
You never initialized alpha, you only declared it, so you can't access alpha[j]. Initialize it and make sure that its size is large enough for every j:
alpha = new double[MY_SIZE];
Also, make sure that you're passing in at least 3 arguments to main so that rotationNum is assigned correctly.
Your class variable alpha is declared, but not initialized, so Java gives it the default value of null. The variable was never initialized to any array.
static double alpha[];
However, it doesn't look like you're using any other intended value in the array except for the current value. Just declare it to be a local double (not an array), and use it as a normal variable.
double alpha = (double)(j-1)*2*Math.PI/(double)rotationNum;
And use alpha instead of alpha[j] a few lines down from there.
You've never initialized alpha[]. Just like pontsR, pointsZ, and chargeDensity, you need to point alpha at a new array of doubles before you can use it.
Add alpha = new double[rotationNum ]; after getting rotationNum
Related
If I run my programme it gives me double numbers, but in the end those numbers aren't like integers anymore because there is a point in them. Can you tell me how to format it or handle this? Thanks
package writingtofile;
import java.io.*;
import java.math.BigInteger;
public class WritingToFile {
public static void main(String[] args) throws IOException {
int counter = 1;
FileWriter out = null;
try{
out = new FileWriter("out.txt");
for(double number : FibanocciNumbers())
{
out.write("Spot:");
out.write(counter + " ");
out.write(String.valueOf(number) + "\r\n");
counter++;
}
}catch(IOException e)
{
System.out.println("Error!");
}
finally
{
out.close();
}
}
public static double[] FibanocciNumbers()
{
double[] fibNumbers = new double[64];
fibNumbers[0] = 1;
fibNumbers[1] = 2;
double lastNumber;
for(int i = 2; i < 64; i++)
{
lastNumber = fibNumbers[i-1];
fibNumbers[i] = lastNumber * 2;
}
return fibNumbers;
Spot:1 1.0
Spot:2 2.0
Spot:3 4.0
Spot:4 8.0
Spot:5 16.0
Spot:6 32.0
Spot:7 64.0
Spot:8 128.0
Spot:9 256.0
Spot:10 512.0
Spot:11 1024.0
Spot:12 2048.0
Spot:13 4096.0
Spot:14 8192.0
Spot:15 16384.0
Spot:16 32768.0
Spot:17 65536.0
Spot:18 131072.0
Spot:19 262144.0
Spot:20 524288.0
Spot:21 1048576.0
Spot:22 2097152.0
Spot:23 4194304.0
Spot:24 8388608.0
Spot:25 1.6777216E7
Spot:26 3.3554432E7
Spot:27 6.7108864E7
Spot:28 1.34217728E8
Spot:29 2.68435456E8
Spot:30 5.36870912E8
Spot:31 1.073741824E9
Spot:32 2.147483648E9
Spot:33 4.294967296E9
Spot:34 8.589934592E9
Spot:35 1.7179869184E10
Spot:36 3.4359738368E10
Spot:37 6.8719476736E10
Spot:38 1.37438953472E11
Spot:39 2.74877906944E11
Spot:40 5.49755813888E11
Spot:41 1.099511627776E12
Spot:42 2.199023255552E12
Spot:43 4.398046511104E12
Spot:44 8.796093022208E12
Spot:45 1.7592186044416E13
Spot:46 3.5184372088832E13
Spot:47 7.0368744177664E13
Spot:48 1.40737488355328E14
Spot:49 2.81474976710656E14
Spot:50 5.62949953421312E14
Spot:51 1.125899906842624E15
Spot:52 2.251799813685248E15
Spot:53 4.503599627370496E15
Spot:54 9.007199254740992E15
Spot:55 1.8014398509481984E16
Spot:56 3.6028797018963968E16
Spot:57 7.2057594037927936E16
Spot:58 1.44115188075855872E17
Spot:59 2.8823037615171174E17
Spot:60 5.7646075230342349E17
Spot:61 1.15292150460684698E18
Spot:62 2.305843009213694E18
Spot:63 4.6116860184273879E18
Spot:64 9.223372036854776E18
So I don't wnat those numbers with points in it, because I think it changes the way you should understand this. How to get them away or handle them? Tanks
This is your code using BigInteger. Its what you want, no decimal!!
also, double is not an integer, its like float but with capability to to hold large fractional numbers. btw you have named it FibanocciNumbers but those are not fibonnaci numbers
import java.io.*;
import java.math.BigInteger;
public class Main {
public static void main(String[] args) throws IOException
{
int counter = 1;
FileWriter out = null;
try{
out = new FileWriter("out.txt");
for(BigInteger number : FibanocciNumbers())
{
out.write("Spot:");
out.write(counter + " ");
out.write(String.valueOf(number) + "\r\n");
System.out.println(number);
counter++;
}
}catch(IOException e)
{
System.out.println("Error!");
}
finally
{
out.close();
}
}
public static BigInteger[] FibanocciNumbers()
{
BigInteger[] fibNumbers = new BigInteger[64];
fibNumbers[0] = new BigInteger("1");
fibNumbers[1] = new BigInteger("2");
BigInteger lastNumber;
for(int i = 2; i < 64; i++)
{
lastNumber = fibNumbers[i-1];
fibNumbers[i] = lastNumber.multiply( new BigInteger("2") );
}
return fibNumbers;
}
}
last line of Output:
Spot:64 9223372036854775808
What would be the java equivalent of the following code?
import scipy
from scipy.stats import zscore
zlist = [9967,11281,10752,10576,2366,11882,11798,]
z = zscore(zlist)
for e in z:
print e,scipy.stats.norm.sf(abs(e))
And the answer is:
private void run() {
double[] values = {9967,11281,10752,10576,2366,11882,11798};
double variance = StatUtils.populationVariance(values);
double sd = Math.sqrt(variance);
double mean = StatUtils.mean(values);
NormalDistribution nd = new NormalDistribution();
for ( double value: values ) {
double stdscore = (value-mean)/sd;
double sf = 1.0 - nd.cumulativeProbability(Math.abs(stdscore));
System.out.println("" + stdscore + " " + sf);
}
}
This is using The Apache Commons Mathematics Library
EDIT: Or, even better:
import java.util.function.BiConsumer;
import org.apache.commons.math3.distribution.NormalDistribution;
import org.apache.commons.math3.distribution.RealDistribution;
import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics;
public class ZScore {
public static void main(String[] args) {
ZScore program = new ZScore();
double[] values = {9967,11281,10752,10576,2366,11882,11798};
program.computeZScoreAndSurvivalFunctions(
new DescriptiveStatistics(values),
new NormalDistribution(),
(zscore, sf)->System.out.println(""+zscore+" "+sf)
);
}
private void computeZScoreAndSurvivalFunctions(
DescriptiveStatistics ds,
RealDistribution dist,
BiConsumer<Double, Double> consumer
) {
double variance = ds.getPopulationVariance();
double sd = Math.sqrt(variance);
double mean = ds.getMean();
for ( int index = 0; index < ds.getN(); ++index) {
double zscore = (ds.getElement(index)-mean)/sd;
double sf = 1.0 - dist.cumulativeProbability(Math.abs(zscore));
consumer.accept(zscore, sf);
}
}
}
I use Eclipse for java programming. I no understand why it gives cannot resolved for (myBox1.width = 10;) to a variable my sample code in below
class Boxf {
double width;
double height;
double depth;
}
class BoxDemo2 {
public static void main(String[] args) {
Boxf mybBox1 = new Boxf();
Boxf mybBox2 = new Boxf();
double vol;
myBox1.width = 10;
myBox1.height = 20.90;
myBox1.depth = 15.75;
vol = myBox1.width * myBox1.height * myBox1.depth;
System.out.println("Volume1 is = "+ vol);
myBox2.width= 10;
myBox2.height = 20.90;
myBox2.depth = 15.75;
vol = myBox2.width * myBox2.height * myBox2.depth;
System.out.println("Volume2 is = "+ vol);
}
Because your instances are mybBox1 (and mybBox2) not myBox1 (and myBox2). The easiest solution I can see is to change this
Boxf mybBox1 = new Boxf();
Boxf mybBox2 = new Boxf();
to
Boxf myBox1 = new Boxf();
Boxf myBox2 = new Boxf();
Another way of doing same thing without using constructor
myBox1.width = 10;
myBox1.height = 20.90;
myBox1.depth = 15.75;
vol = myBox1.width * myBox1.height * myBox1.depth;
u can do the same thing with this code
public void sample ( double width ,double height ,double depth)
{
this.width=width;
this.height=height;
this.depth=depth;
}
After this with the help of object u can access values such that
mybox1.sample(10,20.90,15.75);
mybox2.sample(10,20.90,15.75);
With the help of this pointer u can calculate the volume of box1,box2 . Try this code it will definitely work ...........
I am trying to implement a simple BBands application using talib.
I do not have any expirience in Talib and technical Indicators.
Can someone have a look at say whether this is a good implementation of Bollinger Bands using Talib and give me advice how can it be improved. If anyone has expirience with Talib and Bollinger Bands it would be much appriciated to give me a hand. Here is the code.
import com.tictactec.ta.lib.Core;
import com.tictactec.ta.lib.MInteger;
import com.tictactec.ta.lib.RetCode;
import com.tictactec.ta.lib.*;
import com.tictactec.ta.lib.meta.helpers.*;
public class ExampleTALib
{
/**
* The total number of periods to generate data for.
*/
public static final int TOTAL_PERIODS = 100;
/**
* The number of periods to average together.
*/
public static final int PERIODS_AVERAGE = 20;
public static void main(String[] args)
{
double[] closePrice = new double[TOTAL_PERIODS];
double[] out = new double[TOTAL_PERIODS];
MInteger begin = new MInteger();
MInteger length = new MInteger();
double[] outRealUpperBand = new double[TOTAL_PERIODS];
double[] outRealMiddleBand = new double[TOTAL_PERIODS];
double[] outRealLowerBand = new double[TOTAL_PERIODS];
for (int i = 0; i < closePrice.length; i++) {
closePrice[i] = (double) i;
}
Core c = new Core();
// RetCode retCode = c.sma(0, closePrice.length - 1, closePrice, PERIODS_AVERAGE, begin, length, out);
// RetCode re = c.sma(startIdx, endIdx, inReal, optInTimePeriod, outBegIdx, outNBElement, outReal)
RetCode retCode = c.bbands(0, closePrice.length - 1, closePrice, PERIODS_AVERAGE,
1.0, 3.0, MAType.Ema, begin, length, outRealUpperBand, outRealMiddleBand, outRealLowerBand);
// RetCode re = c.bbands(startIdx, endIdx, inReal, optInTimePeriod, optInNbDevUp, optInNbDevDn, optInMAType, outBegIdx, outNBElement, outRealUpperBand, outRealMiddleBand, outRealLowerBand)
if (retCode == RetCode.Success) {
System.out.println("Output Begin:" + begin.value);
System.out.println("Output Begin:" + length.value);
for (int i = begin.value; i < closePrice.length; i++) {
StringBuilder line = new StringBuilder();
line.append("Period #");
line.append(i+1);
line.append(" close= ");
line.append(closePrice[i]);
line.append(" mov avg=");
line.append(out[i-begin.value]);
System.out.println(line.toString());
}
}
else {
System.out.println("Error");
}
}
}
I've got some code that I don't think is able to be multithreaded, perhaps I'm wrong. I'd like to make execute this code on a clustered system but I'm unsure of how to scale it for such a deployment.
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Coord {
public int a,b,c,d,e,f;
public static void main(String[] args) throws IOException {
FileOutputStream out = new FileOutputStream("/Users/evanlivingston/2b.txt");
PrintStream pout = new PrintStream(out);
Scanner sc = new Scanner(new File("/Users/evanlivingston/1.txt"));
List<Coord> coords = new ArrayList<Coord>();{
// for each line in the file
while(sc.hasNextLine()) {
String[] numstrs = sc.nextLine().split("\\s+");
Coord c = new Coord();
c.a = Integer.parseInt(numstrs[1]);
c.b = Integer.parseInt(numstrs[2]);
c.c = Integer.parseInt(numstrs[3]);
c.d = Integer.parseInt(numstrs[4]);
c.e = Integer.parseInt(numstrs[5]);
c.f = Integer.parseInt(numstrs[6]);
coords.add(c);
}
// now you have all coords in memory
{
for(int i=0; i<coords.size(); i++ )
for( int j=0; j<coords.size(); j++)
{
Coord c1 = coords.get(i);
Coord c2 = coords.get(j);
double foo = ((c1.a - c2.a) * (c1.a - c2.a)) *1 ;
double goo = ((c1.b - c2.b) * (c1.b - c2.b)) *1 ;
double hoo = ((c1.c - c2.c) * (c1.c - c2.c)) *2 ;
double joo = ((c1.d - c2.d) * (c1.d - c2.d)) *2 ;
double koo = ((c1.e - c2.e) * (c1.e - c2.e)) *4 ;
double loo = ((c1.f - c2.f) * (c1.f - c2.f)) *4 ;
double zoo = Math.sqrt(foo + goo + hoo + joo + koo + loo);
DecimalFormat df = new DecimalFormat("#.###");
pout.println(i + " " + j + " " + df.format(zoo));
System.out.println(i);
}
pout.flush();
pout.close();
}
}
}
}
I appreciate any help anyone can offer.
Splitting the inner for loop into separate tasks looks like a good candidate for where to make this process multithreaded. Here is one way this could be done with an ExecutorService and Futures
final ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
final List<Future<String>> results = new LinkedList<Future<String>>();
// now you have all coords in memory
for (int i = 0; i < coords.size(); i++) {
final int index = i;
final Coord c1 = coords.get(index);
results.add(executor.submit(new Callable<String>() {
public String call() {
final StringBuilder stringBuilder = new StringBuilder();
for (int j = 0; j < coords.size(); j++) {
final Coord c2 = coords.get(j);
final double foo = ((c1.a - c2.a) * (c1.a - c2.a)) * 1;
final double goo = ((c1.b - c2.b) * (c1.b - c2.b)) * 1;
final double hoo = ((c1.c - c2.c) * (c1.c - c2.c)) * 2;
final double joo = ((c1.d - c2.d) * (c1.d - c2.d)) * 2;
final double koo = ((c1.e - c2.e) * (c1.e - c2.e)) * 4;
final double loo = ((c1.f - c2.f) * (c1.f - c2.f)) * 4;
final double zoo = Math.sqrt(foo + goo + hoo + joo + koo + loo);
final DecimalFormat df = new DecimalFormat("#.###");
stringBuilder.append(index + " " + j + " " + df.format(zoo));
System.out.println(index);
}
return stringBuilder.toString();
}
}));
}
for (Future<String> result : results) {
pout.print(result.get());
}
pout.flush();
pout.close();
executor.shutdown();
For clustering, I think Hazelcast offers a good solution that will allow you to define a shared ExecutorService and shared Collections. You would need two flavors of nodes, the single node responsible for all I/O and creating the list of Coords as well as submitting the tasks. And a processing node which simply executes the tasks. That is all my opinion of how I might do it. However, if your dataset is small enough to fit in memory it is likely not worth the effort to split up the processing this much.
It looks very parallelizable to me. Why don't you have threads process one row of data at a time? You could use an AtomicInteger to keep a count of how many rows have been claimed by worker threads. Each thread would do a counter.getAndIncrement to get a row to work on (if it returns coords.size() or higher, the thread should terminate), then do all the math for that row, and repeat.
The printing would be out of order, but you could instead fill some buffers with the results, then quickly print everything at the end.