converting c++ DTW code to java - java

I want to translate a code from C++ to Java. The original code implements fast DTW algorithm. The piece of code I couldn't figure out was I attribute I'm not sure what it does hence, I can't convert it.
The error in Java is in statements l_buff+I & u_buff+I because the plus operator is not supported between int I & double[] l_buff,u_buff.
I have included all statements that involves I
int I;
for(i=0; i<ep; i++)
{
/// A bunch of data has been read and pick one of them at a time to use
d = buffer[i];
/// Calculate sum and sum square
ex += d;
ex2 += d*d;
/// t is a circular array for keeping current data
t[i%m] = d;
/// Double the size for avoiding using modulo "%" operator
t[(i%m)+m] = d;
/// Start the task when there are more than m-1 points in the current chunk
if( i >= m-1 )
{
mean = ex/m;
std = ex2/m;
std = Math.sqrt(std-mean*mean);
/// compute the start location of the data in the current circular array, t
j = (i+1)%m;
/// the start location of the data in the current chunk
I = i-(m-1);
lb_k2 = lb_keogh_data_cumulative(order, tz, qo, cb2, l_buff+I, u_buff+I, m, mean, std, bsf);
and the lb_data_cumlative method implementation is
public static double lb_keogh_data_cumulative(int[] order, double []tz, double []qo, double []cb, double []l, double []u, int len, double mean, double std, double best_so_far )
{
double lb = 0;
double uu,ll,d;
for (int i = 0; i < len && lb < best_so_far; i++)
{
uu = (u[order[i]]-mean)/std;
ll = (l[order[i]]-mean)/std;
d = 0;
if (qo[i] > uu)
d = dist(qo[i], uu);
else
{
if(qo[i] < ll)
d = dist(qo[i], ll);
}
lb += d;
cb[order[i]] = d;
}
return lb;
}
here is the paper on which the code relies SIGKDD TRILLION

l_buff+I and u_buff+I mean that you shift the beginning of the arrays to I elements. The lb_keogh_data_cumulative parameters l and u won't see the first I elements of the given arrays.
So you could write something like
lb_k2 = lb_keogh_data_cumulative(order, tz, qo, cb2, Arrays.copyOfRange(l_buff, I, l_buff.length), Arrays.copyOfRange(u_buff, I, u_buff.length), m, mean, std, bsf);
The arrays are not modified by the called method so you can pass a copy.

Related

Understanding why my for loop does not work to approximate e

e can be approximated using the formula e = 1 + (1/1!) + (1/2!) + (1/3!)... + (1/n!). I am trying to use for loops to accept whatever integer the user sets n to be. The program should approximate e by using the formula above from (1/1!) + .... (1/n!) and out put the result.
The nested for loop calculates the factorial of n (tested it separately and it works) and the variable defined, frac, puts the factorial into a fraction of 1/(answer to factorial). I store the value into a variable e and it should add the new fraction to the old value every time an iteration is done. I cannot not understand what is wrong with my loops that they are not out putting the right answer.
System.out.println("Enter an integer to show the result of
approximating e using n number of terms.");
int n=scan.nextInt();
double e=1;
double result=1;
for(int i=1; n>=i; n=(n-1))
{
for(int l=1; l<=n; l++)
{
result=result*l;
}
double frac=(1/result);
e=e+frac;
}
System.out.println(e);
Output when I enter the integer 7 as n = 1.0001986906956286
You don't need that whole inner loop. All you need is result *= i.
for (int i = 1; i <= n; i++)
{
result *= i;
double frac = (1 / result);
e += frac;
}
Here's a JavaScript version I just threw together:
function init() {
const elem = document.getElementById('eapprox');
let eapprox = 1;
const n = 15;
let frac = 1;
for (var i = 1; i <= n; ++i) {
frac /= i;
eapprox += frac;
}
elem.textContent = eapprox;
}
This yields 2.718281828458995. Plunker here: http://plnkr.co/edit/OgXbr36dKce21urHH1Ge?p=preview

Logic behind multiplication method using a 1D Array of LongNumber class

I am having problems with the logic behind this multiplication method. It is using a 1D array of LongNumber. We can't use the Math class, must write our own logic. The two previous methods were addition and subtraction, I am having issues with how to setup the for loop in order to move one num index as we stay at the index of the other, and then changing to the next index of the number that wasn't moved.
This logic has been more confusing for me, addition and subtraction were all in once simple for loop and it was easy, with multiplication I cant figure out how to setup the loop so it only moves num index and not num2, so we can get the correct product.
public static Long_Number multiply(String num,String num2)
{
//data
String resultString3 = "";
Long_Number result3 = new Long_Number("");
int total, carry = 0, temp;
int v1 = 0, v2 = 0;
//set longest length to indexrange
int indexrange = num.length();
if(num2.length()>indexrange)
indexrange = num2.length();
//logic
for(int i = 0; i < indexrange; i++)
{
if(num.length()-1-i >= 0)
v1 = (num.charAt(num.length()-1-i)-'0');
else
v1 = 0;
if(num2.length()-1-i >= 0)
v2 = (num2.charAt(num2.length()-1-i)-'0');
else
v2 = 0;
sumofdigits = v1 * v2 + carry;
carry = sumofdigits % 10;
System.out.println(sumofdigits + "hi" + carry); //test print
}
result3.setNumber(resultString3);
return result3;
}

How to write Extended Euclidean Algorithm code wise in Java?

I have a question which is actually requires a bit of understanding Euclidian Algorithm. Problem is simple. An int "First" and int "Second" numbers are given by the user via Scanner.
Than we need to find greatest common divisor of them. Than the process goes like explained below:
Now Assume that the First number is: 42 and the Second is: 30 - they've given by the user. -
int x, y;
(x * First) + (y * Second) = gcd(First, Second); // x ? y ?
To Find GCD you may use: gcd(First, Second); Code is below:
public static int gcd(int a, int b)
{
if(a == 0 || b == 0) return a+b; // base case
return gcd(b,a%b);
}
Sample Input: First: 24 Second: 48 and Output should be x: (-3) and y: 2
Sample Input: First: 42 Second: 30 and Output should be x: (-2) and y: 3
Sample Input: First: 35 Second: 05 and Output should be x: (0) and y: 1
(x * First) + (y * Second) = gcd(First, Second); // How can we find x and y ?
I would very appreciate it if you could show a solution code wise in java thanks for checking!
The Extended Euclidean Algorithm is described in this Wikipedia article. The basic algorithm is stated like this (it looks better in the Wikipedia article):
More precisely, the standard Euclidean algorithm with a and b as
input, consists of computing a sequence q1,...,
qk of quotients and a sequence r0,...,
rk+1 of remainders such that
r0=a r1=b ...
ri+1=ri-1-qi ri and 0 <
ri+1 < |ri| ...
It is the main property of Euclidean division that the inequalities on
the right define uniquely ri+1 from ri-1 and
ri.
The computation stops when one reaches a remainder rk+1
which is zero; the greatest common divisor is then the last non zero
remainder rk.
The extended Euclidean algorithm proceeds similarly, but adds two
other sequences defined by
s0=1, s1=0 t0=0,
t1=1 ...
si+1=si-1-qi si
ti+1=ti-1-qi ti
This should be easy to implement in Java, but the mathematical way it's expressed may make it hard to understand. I'll try to break it down.
Note that this is probably going to be easier to implement in a loop than recursively.
In the standard Euclidean algorithm, you compute ri+1 in terms of ri-1 and ri. This means that you have to save the two previous versions of r. This part of the formula:
ri+1=ri-1-qi ri and 0 <
ri+1 < |ri| ...
just means that ri+1 will be the remainder when ri-1 is divided by ri. qi is the quotient, which you don't use in the standard Euclidean algorithm, but you do use in the extended one. So Java code to perform the standard Euclidean algorithm (i.e. compute the GCD) might look like:
prevPrevR = a;
prevR = b;
while ([something]) {
nextR = prevPrevR % prevR;
quotient = prevPrevR / prevR; // not used in the standard algorithm
prevPrevR = prevR;
prevR = nextR;
}
Thus, at any point, prevPrevR will be essentially ri-1, and prevR will be ri. The algorithm computes the next r, ri+1, then shifts everything which in essence increments i by 1.
The extended Euclidean algorithm will be done the same way, saving two s values prevPrevS and prevS, and two t values prevPrevT and prevT. I'll let you work out the details.
Thank's for helping me out ajb I solved it after digging your answer. So for the people who would like to see code wise:
public class Main
{
public static void main (String args[])
{
#SuppressWarnings("resource")
System.out.println("How many times you would like to try ?")
Scanner read = new Scanner(System.in);
int len = read.nextInt();
for(int w = 0; w < len; w++)
{
System.out.print("Please give the numbers seperated by space: ")
read.nextLine();
long tmp = read.nextLong();
long m = read.nextLong();
long n;
if (m < tmp) {
n = m;
m = tmp;
}
else {
n = tmp;
}
long[] l1 = {m, 1, 0};
long[] l2 = {n, 0, 1};
long[] l3 = new long[3];
while (l1[0]-l2[0]*(l1[0]/l2[0]) > 0) {
for (int j=0;j<3;j++) l3[j] = l2[j];
long q = l1[0]/l2[0];
for (int i = 0; i < 3; i++) {
l2[i] = (l1[i]-l2[i]*q);
}
for (int k=0;k<3;k++) l1[k] = l3[k];
}
System.out.printf("%d %d %d",l2[1],l2[2],l2[0]); // first two Bezouts identity Last One gcd
}
}
}
Here is the code that I came up with if anyone is still looking. It is in C# but I am sure it similar to java. Enjoy
static void Main(string[] args)
{
List<long> U = new List<long>();
List<long> V = new List<long>();
List<long> W = new List<long>();
long a, b, d, x, y;
Console.Write("Enter value for a: ");
string firstInput = Console.ReadLine();
long.TryParse(firstInput, out a);
Console.Write("Enter value for b: ");
string secondInput = Console.ReadLine();
long.TryParse(secondInput, out b);
long temp;
//Make sure that a > b
if(a < b)
{
temp = a;
a = b;
b = temp;
}
//Initialise List U
U.Add(a);
U.Add(1);
U.Add(0);
//Initialise List V
V.Add(b);
V.Add(0);
V.Add(1);
while(V[0] > 0)
{
decimal difference = U[0] / V[0];
var roundedDown = Math.Floor(difference);
long rounded = Convert.ToInt64(roundedDown);
for (int i = 0; i < 3; i++)
W.Add(U[i] - rounded * V[i]);
U.Clear();
for (int i = 0; i < 3; i++)
U.Add(V[i]);
V.Clear();
for (int i = 0; i < 3; i++)
V.Add(W[i]);
W.Clear();
}
d = U[0];
x = U[1];
y = U[2];
Console.WriteLine("\nd = {0}, x = {1}, y = {2}", d, x, y);
//Check Equation
Console.WriteLine("\nEquation check: d = ax + by\n");
Console.WriteLine("\t{0} = {1}({2}) + {3}({4})", d, a, x, b, y);
Console.WriteLine("\t{0} = {1} + {2}", d, a*x, b*y);
Console.WriteLine("\t{0} = {1}", d, (a * x) + (b * y));
if (d == (a * x) + (b * y))
Console.WriteLine("\t***Equation is satisfied!***");
else
Console.WriteLine("\tEquation is NOT satisfied!");
}
}
}

Usage of BigIntegers and to the power off i

I found out longs wont cut it, as the numbers I'm calculating are to huge to fit. I'm struggling with the concept of BigInts.
Lets say I have the following equation to perform.
int p = 11549
int n = 252817
The equation is as follows.. : ( number * p )^ (to the power of i)%n .
With longs I just did :
long number;
long p;
long n;
long temp;
long total;
for (int i=0; i<6;i++) {
temp = numer*Math.pow(p,i);
total += temp;
}
total %= n;
But when i use Math.pow on I the numbers get to huge to use this method, and I need to use BigIntegers. I Just dont understand how I can do it. Right now I got this : (Missing the % until i can figure out the power off statement.)
long temp;
long p;
BigInteger opphoyd;
BigInteger mod;
for (int i=0;i<6;i++) {
temp = number * p;
opphoyd = BigInteger.valueOf(temp);
mod = BigInteger.valueOf(i);
mod.add(opphoyd.pow(i));
mod.add(opphoyd);
System.out.println(mod);
}
But its not working at all, could anyone point me in the right direction?
BigInteger's add method (and most of the other methods) does not modify the BigInteger it is called on. Instead it returns a new BigInteger.
So you would need to do:
BigInteger sum = mod.add(opphoyd);
Take a look at the javadocs, it will be very helpful when working with BigInteger.
long temp;
long p;
BigInteger opphoyd;
BigInteger mod;
for( int i = 0; i < 6; i++ ) {
temp = number * p;
opphoyd = BigInteger.valueOf(temp);
mod = BigInteger.valueOf(i);
BigInteger sum = mod.add( opphoyd.pow(i));
sum = sum.add(opphoyd);
System.out.println( sum );
}

Converting Complex to ArrayList<Float> in Java

I have an input signal that I want to store in an ArrayList then convert it into Complex, which goes something like this
-0.03480425839330703
0.07910192950176387
0.7233322451735928
0.1659819820667019
and this outputs its FFT like this
0.9336118983487516
-0.7581365035668999 + 0.08688005256493803i
0.44344407521182005
-0.7581365035668999 - 0.08688005256493803i
This is in a complex structure, I want to convert this into an ArrayList type. while dropping the + 0.08688005256493803i value.
So All I need are these values
0.9336118983487516
-0.7581365035668999
0.44344407521182005
-0.7581365035668999
What is the best way of going about this?
And this is the code that I am using
public static Complex[] fft(Complex[] x) {
int N = x.length;
// base case
if (N == 1) return new Complex[] { x[0] };
// radix 2 Cooley-Tukey FFT
if (N % 2 != 0) { throw new RuntimeException("N is not a power of 2"); }
// fft of even terms
Complex[] even = new Complex[N/2];
for (int k = 0; k < N/2; k++) {
even[k] = x[2*k];
}
Complex[] q = fft(even);
// fft of odd terms
Complex[] odd = even; // reuse the array
for (int k = 0; k < N/2; k++) {
odd[k] = x[2*k + 1];
}
Complex[] r = fft(odd);
// combine
Complex[] y = new Complex[N];
for (int k = 0; k < N/2; k++) {
double kth = -2 * k * Math.PI / N;
Complex wk = new Complex(Math.cos(kth), Math.sin(kth));
y[k] = q[k].plus(wk.times(r[k]));
y[k + N/2] = q[k].minus(wk.times(r[k]));
}
return y;
}
All you want to do is just drop imaginary part of your Complex data structure.
As you not show us Complex class assume it has member for real part (e.g double real;)
To drop imaginary part just call something like complex.getRealPart(), or access complex.real (substitute with your real member name).
To compose ArrayList<Double> use the following snippet:
ArrayList<Double> list = new ArrayList<Double>();
for (Complex c : complexes) { // complexes your array of complexes returned from for fft
list.add(c.getRealpart());
}
Note: Just in case, I can be wrong, but I assume that instead of real part you need absolute value of complex number. To calculate it use:
Math.sqrt(c.getRealPart() * c.getRealPart() + c.getImPart() * c.getImPart());
From what I understand you just want the real part of the complex value. If that's the case, presumably your Complex class also has getReal() and getImaginary() (or similar) methods - so just use getReal().

Categories

Resources