Setting up array of complex coefficients, avoiding the leading zero's - java

I have created a class for complex numbers:
public class Complex {
private double x; //Real part x of the complex number x+iy.
private double y; //Imaginary part y of the complex number x+iy.
public Complex(double x, double y) { //Constructor: Initializes x, y.
this.x=x;
this.y=y;
}
public Complex(double x) { //Real constructor - initialises with a real number.
this(x, 0.0);
}
public Complex() { //Default constructor; initialiase x and y to zero.
this(0.0, 0.0);
}
}
What I would like to do is create a function Polynomial, which would take an array of coefficients, and filter it so that if for example [1,0,0,1,0,0,0,0,0...], it would return an array of length 4. Since the zero's that are left, have no use in a polynomial.
Here's how a complex array would look like
Complex [] coeff = new Complex [] {
new Complex(-1.0 ,0.0), new Complex(),
new Complex() , new Complex(1.0, 0.0)
};
A polynomial would be defined as
Polynomial p = new Polynomial(coeff);
Here's the problem formulation:
Here is how the polynomial would have to look like, typing in the complex array coefficients
I was thinking of constructing an algorithm which searches for the first zero of the zero sequence(which is until the end of the array), and then deletes the zeros.
Also I was thinking of inverting the entries of the array so that [0,1,1,0,1,0,0,0] would be [0,0,0,1,0,1,1,0] and then creating a function which would start "recording" my new array from the first non Trivial entry.
How would I go with creating such a function?
My attempt for this is:
int j=0;
for(int i=coeff.length-1; i>=0; i-=1)
{
if(coeff[i].getReal()== 0 && coeff[i].getImag() == 0 ){
j=+1;
}
else {
break;
}
}
int a = coeff.length-j;
this.coeff = new Complex[a];
for (int i=0;i<this.coeff.length;i+=1){
this.coeff[i]=coeff[i];
}
}
And for example I would like to print :
Complex a1=new Complex(-3, 1);
Complex a2=new Complex(2, 0.3);
Complex a3=new Complex();
Complex b=new Complex();
Complex[] com=new Complex[] {a1,b, a2, a3,b};
and the output is :
(-3.0+1.0i)+ (0.0+0.0i)X^1+(2.0+0.3i)X^2+(0.0+0.0i)X^3
But is supposed to be :
(-3.0+1.0i)+ (0.0+0.0i)X^1+(2.0+0.3i)X^2
And I've tried adding a "-1" to int a = coeff.length-j; :
int a = coeff.length-j-1;
but then if i print out
Complex[] com=new Complex[] {a1,b, a2, a3,b,b,b,b,b,b};
It's going to give me the same results (ie storing the trivial coefficients).
How can i make the contructor not store those trivial coefficients?

I think that the way to go in here is by iterating over the Array for the end to the start, just like you were trying. The problem with your code is the next:
if(coeff[i].getReal()== 0 && coeff[i].getImag() == 0 ){
j=+1; //Here! I think you wanted to do j+=1
}
At doing j=+1 you are making j to always have a value of 1. So, changing j=+1 to j+=1 will fix this.
Also, I did a different code if you want to check it. At the end, it does the same but I think is cleaner.
public class Polynomial {
private Complex[] coeff;
public Polynomial(Complex[] coeff) {
this.coeff = cleanCoeff(coeff);
}
private Complex[] cleanCoeff(Complex[] coeff) {
int length = coeff.length;
Complex complex = null;
for (int i = coeff.length - 1; i >= 0 ; i--) {
complex = coeff[i];
if(complex.getX() == 0 && complex.getY() == 0) {
length--;
}else {
break;
}
}
return Arrays.copyOf(coeff, length);
}
public Complex[] getCoeff() {
return coeff;
}
}
I hope this answer helps you.

This could be done relatively easily using something like the following:
int effective_len(Complex coeff[]) {
int pos = 0;
Complex zero();
for (int i=0; i<coeff.lengh; i++) {
if (!zero.equals(coeff[i])) {
pos = i;
}
}
return pos + 1;
}
For this you will need to define the equals method where you just check the real and imaginary components, but this should get you where you need to go.

Related

Java, Creating an object vector that should have n zeros in it's array after compilation

This is kind of hard but I will try to make my question as clear as possible.
So I'm working on a project that deals with operations on vectors. I have different classes for different dimensions: Vector3D, Vector5D and VectorND. So I have interface and abstract class that describe methods like Sum, Subtraction etc. And for result of operation I create a new object Vector where I put coordinates after sum/subtraction etc. So here is the part of code as an example:
interface sample
{
Vector Sum(Vector vec);
Vector Subtraction(Vector vec);
int Product(Vector vec);
boolean Compare(Vector vec);
String ToString();
}
abstract class Vector implements sample
{
int[] coordinates;
public Vector (int[] coordinates)
{
this.coordinates=coordinates;
}
protected abstract Vector resVec();
public Vector Sum(Vector vec)
{
Vector result = resVec();
if (this.coordinates.length == vec.coordinates.length)
{
for (int i = 0; i< vec.coordinates.length; i++)
{
result.coordinates[i] = this.coordinates[i] + vec.coordinates[i];
}
}
else
{
throw new ArithmeticException("Can't sum vectors of different length");
}
return result;
Here is have protected abstart Vector resVec(); - method that creates new vector with length that depends on dimension of vectors that we operate with.
Example of realization for Vector3D:
class Vector3D extends Vector
{
public Vector3D(int n1,int n2,int n3)
{
super(new int[]{n1,n2,n3});
}
public Vector3D resVec()
{
Vector3D resVec = new Vector3D(0,0,0);
return resVec;
}
So here I create a new vector with length 3 and fill it with zeros. I need to create same vector for VectorND. Like this:
class VectorND extends Vector
{
public VectorND(int...n)
{
super(n);
}
public VectorND resVec()
{
VectorND resVec = new VectorND();
return resVec;
}
Any ideas how I can pass not declared number of zeros? Or maybe any idea of different implementation? Thanks!
Within the resVec() method, you can populate an array of 0s and then pass it to your Vector super constructor. Since your super constructor takes an array of ints, you could do something like this:
public VectorND resVec(int n)
{
int[] coordinates = new int[n];
Arrays.fill(coordinates, 0);
VectorND resVec = new VectorND(coordinates);
return resVec;
}
Foremost you could make use of generics since you would get problems as soon you need float or double for a vector type.
public interface Vector<T extends Number>{
T getX();
void setX(T x);
// [...]
T length();
T lengthSquared();
// [...]
To your problem, it can be solved by adding a helper variable which contains the dimension amount and than process the math operations as algorthm / loop. This way the amount of dimension don't matter anymore and you also avoid issues like divide by zero.
this is a excample for a matrix .. but the aproche is the same:
public final void multiply(float factor) {
// in your case it would be getDimension() or something
for(int i = 0; i < getRows()*getColumns();++i){
m[i]*=factor;
}
}
Oh and I know this advice is hard for java developer but don't over engineer it otherwise you will waste preformence.
The values of arrays are automatically defaulted.
int[] ints = new int[4]; // Filled with 0
double[] doubles = new double[5]; // Filled with 0.0
boolean[] booleans = new boolean[6]; // Filled with false
String[] strings = new String[7]; // Filled with null
I am not entirely sure about your classes, but for a multi-dimensional matrix-like class one only needs one version. The values can be stored in a linearized array by using a calculated index.
public class DoubleMatrix {
final int[] sizes;
final double[] values;
public DoubleMatrix(int... sizes) {
this.sizes = Arrays.copyOf(sizes, sizes.length); // Or sizes.clone()
int valueCount = 1;
for (int size : this.sizes) {
assert size > 0 : "Every given size must be at least 1.";
valueCount *= size;
}
values = new int[valueCount];
}
public int dimesion() {
return sizes.length;
}
public double get(int... is) {
int i = index(is);
return values[i];
}
// new DoubleMatrix(2, 3, 4).set(3.14259, 0, 1, 2); // 24 values in 3D
public void set(double x, int... is) {
int i = index(is);
values[i] = x;
}
The setter is a bit unconventional placing the value first because of the var-args is.
The linearisation from several indices to an index into the values array:
private int index(int... is) {
assert is.length == sizes.length: "Wrong number of indices.";
int singleI = 0;
for (int dim = 0; dim < sizes.length) {
if (0 > is[dim] || is[dim] >= sizes[dim]) {
throw new IndexOutOfBoundsException();
}
if (dim > 0) {
singleI *= sizes[i - 1];
}
singleI += is[i];
}
}
(I am not sure the index calculation is correct.)
Instead of asserts throwing runtime exceptions (IllegalArgumentException) would be better.
Of course if get and set were protected you could make a child class without var-args, and have a public get(int i, int j) for a DoubleMatrix2D.

Tridiagonal matrix algorithm /Thomas algorithm issues

I am pretty new to programming and struggling with my Java code for the tridiagonal matrix algorithm.
The tridagonal matrix is formed as a double array, length 3 at the 1st level, lengths n-1,n and n-1 respectively at the 2nd level
The code compiles but is not producing the right vector. Was wondering if someone can spot the error. Also there is a divisibility by 0 issue in the formula, is there some way to get around this? I have seen this algorithm in other languages but am not experienced enough to see the error! Thanks for your help
static double [] linearSolve( double [][] T, double [] v)
{
double []x ;
x= new double [v.length];
if (T== null || v == null)
{
x = null;
}
else if (isValidTridiagonal(T)== true && v.length==T[1].length)
{
T[0][0]=T[0][0]/T[1][0];
v[0]= v[0]/T[1][0];
x = new double [v.length];
for (int j=1;j<v.length-1;j++)
{
double d = 1.0/(T[1][j]-(T[0][j-1]*T[2][j]));
T[0][j]= T[0][j]*d;
v[j]= v[j]-(T[2][j]*v[j-1]*d);
}
x[v.length-1]=v[v.length-1];
for(int j=v.length-2;j!=-1;j--)
{
x[j]=v[j]-T[0][j]*x[j+1];
}
return x;
}
else
{
x =null;
}
return x;
}

Generic Number Tweening (Help me do one strange trick..)

I am trying to make as generic as possible method for tweening between various types of values.
So, given a start and end value thats, say, either an Int,Float or Double as well as the number of steps (int), it will return values evenly distributed along those steps in the same type.
However, I am starting to suspect;
a) My knowledge of generics is terrible.
b) This might not be possible :(
So, just to be clear, one example;
SpiffyTween<Double> meep = new SpiffyTween<Double>(1d,10d, 100);
while (meep.hasNext()){
Log.info("value="+meep.next());
}
Would return 0.0,0.1,0.2..etc upto 9.9
But SpiffyTween could also work with other number types without needing separate code for each.
Heres the code I have right now;
class SpiffyTween<T extends Number> implements SpiffyGenericTween<T>
{
static Logger Log = Logger.getLogger("SpiffyTween <Number>");
private T start;
private T end;
int totalsteps=0;
int CurrentStep = 0;
ArrayList<T> steps = new ArrayList<T>();
public SpiffyTween(T start,T end, int steps) {
this.start = start;
this.end = end;
this.totalsteps = steps;
precalculate();
}
private void precalculate() {
//calc step difference
double dif = ((end.doubleValue() -start.doubleValue())/totalsteps);
Log.info("dif="+dif);
int i=0;
while(i<totalsteps){
T stepvalue = (T)((Number)(start.doubleValue() +(dif*i)));
steps.add(stepvalue);
Log.info("add step="+stepvalue);
i++;
}
}
public T next(){
T currentVal = steps.get(CurrentStep);
CurrentStep++;
return currentVal;
}
#Override
public boolean hasNext() {
if (CurrentStep<totalsteps){
return true;
}
return false;
}
}
This works...ish.
While the numbers come out aproximately right occasionally theres values like;
9.600000000000001
or
2.4000000000000004
I am assuming thats to do with the unchecked type conversion here;
T stepvalue = (T)((Number)(start.doubleValue() +(dif*i)));
But I cant work out how to do it better.
Whatever the solution (if theres one), my longterm plan is to try to make similar code that can also work on arrays of various number types. So, you could tween between 3 dimensional points by feeding it an array of the x/y/z co-ordinates of the start and end.
Also, possibly more relevantly, in the code example here its basic addition being done. I probably want other types of tweening possible, so that would make the maths more complex.
Is the better route to convert to, say, BigNumber, and then (somehow) back to the initial T later after all the processing is done?
Thanks in advance for any help or pointers.
YOu don't really need Generics to write code once. Consider the code below. Your exercise is to extend to other dimensions and to ensure caller does not use less than one step:
Tween Class
package com.example.stepup;
public class Tween {
public static int[] get1DimSteps (int start, int end, int steps) {
double[] preciseResult = get1DimSteps((double) start, (double) end, steps);
int[] result = new int[steps];
for (int i=0; i<steps; i++) {
result[i] = (int) (preciseResult[i] + 0.5D);
}
return result;
}
public static double[] get1DimSteps (float start, float end, int steps) {
double[] result = get1DimSteps((double)start, (double)end, steps);
return result;
}
public static double[] get1DimSteps (double start, double end, int steps) {
double distance;
double stepSize;
double[] result = new double[steps];
distance = end - start;
stepSize = distance / steps;
for (int i=0; i < steps; i++) {
result[i] = start + stepSize*i;
}
return result;
}
}
StepupTest Class
package com.example.stepup;
public class StepupTest {
public static void main(String[] args) {
// get steps from "start" to "finish"
int startI = -1;
int endI =999;
float start = (float) startI;
float end = (float) endI;
double startD = (double) startI;
double endD = (double) endI;
int numberOfSteps = 100;
double[] steps = Tween.get1DimSteps( start, end, numberOfSteps);
double[] stepsD = Tween.get1DimSteps(startD, endD, numberOfSteps);
int[] stepsI = Tween.get1DimSteps(startI, endI, numberOfSteps);
for (int i=0; i < numberOfSteps; i++) {
System.out.println(" " + i + ". " + steps[i] + ", " + stepsD[i] + ", " + stepsI[i]);
}
}
}

Array of arbitrary dimension as method parameter

I have a simple converter method for an array from boolean to int:
public static int[] convert1dToInt (boolean[] x) {
int la = x.length;
int[] y = new int[la];
for (int a = 0; a < la; a++) {
if (x[a]) {
y[a] = 1;
} else {
y[a] = 0;
}
}
return y;
}
Now I have the same method for 2-dimensional arrays:
public static int[][] convert2dToInt (boolean[][] x) {
int la = x.length;
int lb = x[0].length;
int[][] y = new int[la][lb];
for (int a = 0; a < la; a++) {
for (int b = 0; b < lb; b++) {
if (x[a][b]) {
y[a][b] = 1;
} else {
y[a][b] = 0;
}
}
}
return y;
}
How can I generalize those methods for arrays of arbitrary dimension without writing all the methods by hand?
This is possible, but reflection and recursion are both inevitable:
import java.lang.reflect.Array;
public class ArrayTransfer {
private static int getArrayDimension(Object array) {
Class<?> clazz = array.getClass();
int dimension = 0;
while (clazz.isArray()) {
clazz = clazz.getComponentType();
dimension += 1;
}
if (clazz != boolean.class) {
throw new IllegalArgumentException("Base array type not boolean");
}
return dimension;
}
// Transfers a boolean array of the specified dimension into an int
// array of the same dimension.
private static Object transferToIntArray(Object booleanArray, int dimension) {
if (booleanArray == null) {
return null;
}
// Determine the component type of the new array.
Class<?> componentType;
if (dimension == 1) {
componentType = int.class;
} else {
// We have a multidimensional array; the dimension of the component
// type is one less than the overall dimension. Creating the class
// of an array of an unknown dimension is slightly tricky: we do
// this by creating a 0 x 0 x ... x 0 array (with dimension - 1
// zeros) and then getting the class of this array. Handily for us,
// int arrays are initialised to all zero, so we can create one and
// use it straight away.
int[] allZeroDimensions = new int[dimension - 1];
componentType = Array.newInstance(int.class, allZeroDimensions).getClass();
}
// Create the new array.
int length = Array.getLength(booleanArray);
Object newArray = Array.newInstance(componentType, length);
// Transfer the elements, recursively if necessary.
for (int i = 0; i < length; ++i) {
if (dimension == 1) {
Boolean value = (Boolean)Array.get(booleanArray, i);
Array.set(newArray, i, (value.booleanValue()) ? 1 : 0);
}
else {
Object oldChildArray = Array.get(booleanArray, i);
Object newChildArray = transferToIntArray(oldChildArray, dimension - 1);
Array.set(newArray, i, newChildArray);
}
}
return newArray;
}
// Transfers a boolean array of some dimension into an int
// array of the same dimension.
public static Object transferToIntArray(Object booleanArray) {
if (booleanArray == null) {
return null;
}
int dimension = getArrayDimension(booleanArray);
return transferToIntArray(booleanArray, dimension);
}
}
This should work with any number of dimensions up to 255 - I gave it a quick test with 5 and it seemed to work. It should also work with 'jagged' arrays, and with nulls.
To use it, call ArrayTransfer.transferToIntArray(...) with your boolean array, and it will return the corresponding int array. You will of course need to cast the return value of this method to the relevant int array type.
There's certainly scope for improving this. In particular, it would be nicer if some cache of the various array classes was kept, rather than having to instantiate empty arrays just to get their class.
You can use a conditional recursivity on the type of the passed parameter and you use convert1dToInt for the dimension one , then you collect the result in one object, in the given context you will be forced to pass just an object of type Object and return an Object then you cast it , here is a small code that present idea of the recursive function that just print the value of the elements in the array :
public static void convertDimN(Object o) {
if (o.getClass().isArray() && Array.get(o, 0).getClass().isArray()) {
// is o a two dimentional array
for (int i = 0; i < Array.getLength(o); i++) {
convertDimN(Array.get(o, i));
}
} else
for (int i = 0; i < Array.getLength(o); i++) {
System.out.println(Array.get(o, i));
}
}
This would be your first method:
public static int[] convert1dToInt (boolean[] x) {
//int la = x.length; is useless since you are accessing an object member and not a method
int[] y = new int[x.length];
for (int a = 0; a < x.length; a++) {
y[a] = x[a] ? 1 :0;
}
return y;
}
Simply reuse your code - I had not much time since it is my lunch break so I don#t know if all is correct but the way should fit:
public static int[][] convert2dToInt (boolean[][] x) {
int[][] y = new int[x.length][];
for (int a = 0; a < x.length; a++) {
y[a] = convert1dToInt (x[a]) ;
}
return y;
}
Ok, this solution was not the answer for the problem since I did not read exactly what has been asked. Sorry for that. As far as I know a generalized method is not possible as long as you are working with primitive datatypes. This is because you can't add an int[] as a member for an int[]. So you should then work with Object[], Boolean[] and Integer[] but I don't know how you want to work with that. I don't think it is sensible to write such a method because when you are able to convert such a data-structure how do you want the targets to be accessed. Since you do not know how many dimensions your array will have you can't write generic methods to access the members. I will try to write a solution for that since I want to know if I find an other possible solution. Am I right that the question is, if it is possible and not if it is reasonable?
I think we can find the best solution for that if you tell us the usecase you want to have this code for. As I said, when I have more time later on I'll try to find another solution.

Parallel Programming Assignment in java

I am busy on a parallel programming assignment, and I am really stuck. To be honest I am not entirely sure how each method works, but I think I have an idea.
I need to sum an array of consecutive values (in parallel). Seems easy enough, but I get 0 as an answer every time I try. I really don't know why.
class SumThreaded extends RecursiveTask<Integer> {
static int SEQUENTIAL_THRESHOLD = 10000;
double lo=0.0;
double hi=0.0;
long[] arr;
public SumThreaded(long[] array, double a, double b) {
arr=array;
lo=a;
hi=b;
}
public Integer compute() {
//System.out.println(mid);
if(hi - lo <= SEQUENTIAL_THRESHOLD) {
int ans = 0;
for(int i= (int) lo; i < hi; ++i)
ans += arr[i];
return ans;
}
else {
SumThreaded left = new SumThreaded(arr,lo,(hi+lo)/2.0);
SumThreaded right = new SumThreaded(arr,(hi+lo)/2.0,hi);
left.fork();
int rightAns = right.compute();
int leftAns = left.join();
return leftAns+rightAns;
}
}
public static void main(String args[]){
int size = 1000000;
long [] testArray=new long[size];
for(int i=0;i<size;i++){
testArray[i]=i+1;
}
SumThreaded t = new SumThreaded(testArray,0.0,testArray.length);
ForkJoinPool fjPool = new ForkJoinPool();
int result =fjPool.invoke(t);
System.out.println(result);
}
}
Any help would be greatly appreciated.
Your problem appears to be that you have two separate constructors for SumThreaded, only one of which sets the class's fields. When you're feeding in the long[] array from the new in sumArray, you throw the array away. You need to pick whether you're using ints or longs (and the sum of a big array is likely to need a long) and then make sure your values are getting set appropriately. Debugging and setting a breakpoint on compute would have shown you this.

Categories

Resources