Digital Filter, Math in Java, - java

I need your help, and thank you for reading my question!
I am currently writing a java Programm that will use an Direket Form 2 Transposed Filter. I know that the function filter in Matlab will do that just fine, but i have to use Java.
So does anyone know you to implement this Direkt Form 2 Transposed , this Math Function:
y(n) = b(1)*x(n) + b(2)*x(n-1) + ... + b(nb+1)*x(n-nb)
- a(2)*y(n-1) - ... - a(na+1)*y(n-na)
in any Programmm Language? All it takes is hopefully a point to the wrigth direction so i can figure it out! Maybe there is an C Lib that implements some of the matlab functions, just anything.
So thank you for your time
yours Elektro
Follow up:
I tried for a couple of days to understand your function but i couldn't.
This is the function from Matlab: filter
http://www.mathworks.com/access/helpdesk/help/techdoc/index.html?/access/helpdesk/help/techdoc/ref/filter.html&http://www.google.de/search?hl=de&q=filter+matlab&btnG=Google-Suche&meta=&aq=f&oq=
All i know is that i use in matlab the function like this:
newArray = filter(1,LPC_Faktor,OldArray)
All I have to do is to implement the filter function.
So could you help again?
Thanks
Elektro

Whatever language you use, the direct form II transposed structure is quite simple.
For example, in C, it could be something like:
float myFilter( float u)
{
static float[nb] x = {0,0,0,...,0); // initialize x
static float[na] y = {0,0,0,...,0); // initialize y
static float b1 = ....; // put b(1) here
static float[nb] b = {...,...,...,...,...}; // put b(2) to b(nb+1) here
static float[na] a = {...,...,...,...,...}; // put a(2) to a(na+1) values here
// initialization
float sum = 0;
int i=0;
// compute the value
for(i=0;i<nb;i++)
sum += b[i]*x[i];
for(i=0;i<na;i++)
sum -= a[i]*y[i];
sum += b1*u;
// prepare the values for the next time
for(i=1;i<nb;i++)
x[i] = x[i-1];
x[0] = u;
for(i=1;i<na;i++)
y[i] = y[i-1];
y[0] = sum;
// return the value
return sum;
}
I did not test the code, but it is something like that.
The Direct Form II transposed is the simplest form to implement a FIR filter (numerically, and specially in fixed-point, it is not the best, but it is the form that requires the less operations).
Of course, it is possible to have a better implementation (with cycling array, for example). If needed, I can provide it, too.
EDIT: I answered too quickly. The algorithm you provide
y(n) = b(1)x(n) + b(2)x(n-1) + ... + b(nb+1)x(n-nb) - a(2)y(n-1) - ... - a(na+1)*y(n-na)
is not the Direct Form II, but the direct form I. It requires to store na+nb values (n is the order of your filter), whereas the Direct Form II requires only max(na,nb).
The algorithm used for the Direct Form II is
e(n) = u(n) - a(1)*e(n-1) - a(2)*e(n-2) - ... - a(na)*e(n-na)
y(n) = b(1)*e(n-1) + b(2)*e(n-2) + ... + b(nb)*e(n-nb)
Tell me if you need this form or not.

after long searching i found the answer,
thank you showed the rigth way:
filter(int ord, float *a, float *b, int np, float *x, float *y)
{
int i,j;
y[0]=b[0] * x[0];
for (i=1;i<ord+1;i++)
{
y[i]=0.0;
for (j=0;j<i+1;j++)
y[i]=y[i]+b[j]*x[i-j];
for (j=0;j<i;j++)
y[i]=y[i]-a[j+1]*y[i-j-1];
}
/* end of initial part */
for (i=ord+1;i<np+1;i++)
{
y[i]=0.0;
for (j=0;j<ord+1;j++)
y[i]=y[i]+b[j]*x[i-j];
for (j=0;j<ord;j++)
y[i]=y[i]-a[j+1]*y[i-j-1];
}
} /* end of filter */

Related

Trying to convert this formula into an arithmetic expression in Java

I'm trying to take user input in the form of myMonthlyPayment, myAnnualInterestRate, and myPrincipal in order to calculate the number of months needed to pay off debt by using The formula I've attached to this post. What I have in eclipse for the formula right now is:
monthsNeeded = ((Math.log(myMonthlyPayment) - Math.log(myMonthlyPayment)
- ((myAnnualInterestRate / 1200.0) * myPrincipal))
/ ((Math.log(myAnnualInterestRate) / 1200.0) + 1.0));
I should be getting an output of 79 months with the inputs I'm using but instead I'm getting -62. I know the formula is correct, I'm almost positive I've made a mistake somewhere in the translation of it into Java. If someone could point it out that would be greatly appreciated!
So I've fixed it, with a sample input and output.
I didn't put much effort into making this code beautiful but you can see that even separating it into 3 parts using method extraction (although I didn't know how to name them, lacking the domain knowledge) made the code easier to understand.
public class Example {
public static void main(String[] args) {
double myMonthlyPayment = 2000;
double myAnnualInterestRate = 5;
double myPrincipal = 200000;
System.out.println(a(myMonthlyPayment));
System.out.println(b(myPrincipal, myAnnualInterestRate, myMonthlyPayment));
System.out.println(c(myAnnualInterestRate));
double monthsNeeded = (a(myMonthlyPayment) - b(myPrincipal, myAnnualInterestRate, myMonthlyPayment))
/ c(myAnnualInterestRate);
System.out.println(monthsNeeded);
}
private static double c(double myAnnualInterestRate) {
return Math.log((myAnnualInterestRate / 1200.0) + 1);
}
private static double b(double myPrinicipal, double myAnnualInterestRate, double myMonthlyPayment) {
return Math.log(myMonthlyPayment - (myAnnualInterestRate / 1200.0) * myPrinicipal);
}
private static double a(double myMonthlyPayment) {
return Math.log(myMonthlyPayment);
}
}
I think this is what you're looking for:
monthsNeeded = (Math.log(myMonthlyPayment) - Math.log(myMonthlyPayment - myAnnualInterestRate / 1200d * myPrincipal)) / Math.log(myAnnualInterestRate / 1200d + 1);
It seems that, in your solution, you weren't calculating your myAnnualInterestRate/1200*myPrincipal inside your second Math.log(...). You had also left some calculations outside of Math.log(...) in the bottom half of your equation.
If you have an equation that does an operation inside a natural log, when you convert that equation to Java code, the operation needs to still be done, inside the natural log:
ln(someNumber + 10)
would be converted to:
Math.log(someNumber + 10),
NOT:
Math.log(someNumber) + 10
Hope this helps and good luck. :)

Chudnovsky algorithm

I tried to make a program (in Java) that calculates pi with the Chudnovsky algorithm but it has the output NaN (Not a Number). Please help me find mistakes in my code, or improve my code. (I don't have a lot of Java programming knowledge)
You can find Chudnovsky's algorithm here:
https://en.wikipedia.org/wiki/Chudnovsky_algorithm
here is my code:
package main;
public class Class1 {
public static void main(String[] args)
{
double nr1=0,nr2=0,nr3=0,pi=0;
int fo1=1, fo2=1, fo3=1;
for(int i=0; i<=20; i++){
for(int fl1=1; fl1<=(6*i); fl1++){fo1 = fo1 * fl1;}
for(int fl2=1; fl2<=(3*i); fl2++){fo2 = fo2 * fl2;}
for(int fl3=1; fl3<=(i); fl3++){fo3 = fo3 * fl3;}
nr1 = ( (Math.pow(-1, i)) * (fo1) * ((545140134*i) + 13591409) );
nr2 = ( (fo2) * (Math.pow(fo3, i)) * ( Math.pow(Math.pow(640320, 3), (i+(1/2)) )) );
nr3 = 12 * (nr1/nr2);
}
pi = 1/nr3;
System.out.println((Math.PI));
System.out.println(pi);
}
}
There are many issues here.
As Andy mentioned, 1/2 is not 0.5.
You are using integers to compute things like 120! which is completely out of bounds for any primitive type.
f01,f02,f03 should be initialized inside each loop, otherwise they grow even bigger
It is not trivial to fix it. You can take a look at
Error calculating pi using the Chudnovsky algorithm - Java
and
http://www.craig-wood.com/nick/articles/pi-chudnovsky/
for some hints, but don't expect built-in primitive types to work with that algorithm.

Float.floatToIntBits in php or the right way pass int value inside a float

I need to pass an int value inside a float from java code to php.
The reason is that the third-party API that I have to use in between accepts only float values.
In java I have the following code, that works as expected:
int i1 = (int) (System.currentTimeMillis() / 1000L);
float f = Float.intBitsToFloat(t);
int i2 = Float.floatToIntBits(f);
//i1 == i2
Then I pass float value from Float.intBitsToFloat() to the third-party API and it sends a string to my server with float:
"value1":1.4237714E9
In php I receive and parse many such strings and get an array:
{
"value1" => 1.4237714E9, (Number)
"value2" => 1.4537614E9 (Number)
...
}
Now I need to make Float.floatToIntBits() for each element in php, but I'm not sure how. Will these php numbers be 4 bytes long? Or maybe I can somehow get integer while parsing from string? Any suggestions?
Thank you in advance!
Thank you, guys! Yes, I forgot about pack/unpack.
It's not really an answer, yet it works for my case:
function floatToIntBits($float_val)
{
$int = unpack('i', pack('f', $float_val));
return $int[1];
}
But not vice versa! The strange thing:
$i1 = 1423782793;
$bs =pack('i', $i);
$f = unpack('f', $bs);
//array { 1 => 7600419110912} while should be 7.6004191E12 (E replaced with 109?)
//or may be 7600419110000 which also right, but not 7600419110912!
I can't explain this. Double checked on home system and on server (5.5 and 5.4 php) - the same result.
Hi the staff that I found you probably will not like:
function FloatToHex1($data)
{
return bin2hex(strrev(pack("f",$data)));
}
function HexToFloat1($data)
{
$value=unpack("f",strrev(pack("H*",$data)));
return $value[1];
}
//usage
echo HexToFloat1(FloatToHex1(7600419100000));
Give the result like 7600419110912
so the 109 is NOT a substitution of E the problem is recalculation of the numbers with float point. It's sounds funny but PHP recalculation bring you the most accurate answer possible. And this is an answer 7600419110912
So read this post for more info https://cycling74.com/forums/topic/probably-a-stupid-question-but/

Coefficient Correlation Over a Large Binary Image Data-Set - Slow Performance

I am trying to build an OCR by calculating the Coefficient Correlation between characters extracted from an image with every character I have pre-stored in a database. My implementation is based on Java and pre-stored characters are loaded into an ArrayList upon the beginning of the application, i.e.
ArrayList<byte []> storedCharacters, extractedCharacters;
storedCharacters = load_all_characters_from_database();
extractedCharacters = extract_characters_from_image();
// Calculate the coefficent between every extracted character
// and every character in database.
double maxCorr = -1;
for(byte [] extractedCharacter : extractedCharacters)
for(byte [] storedCharacter : storedCharactes)
{
corr = findCorrelation(extractedCharacter, storedCharacter)
if (corr > maxCorr)
maxCorr = corr;
}
...
...
public double findCorrelation(byte [] extractedCharacter, byte [] storedCharacter)
{
double mag1, mag2, corr = 0;
for(int i=0; i < extractedCharacter.length; i++)
{
mag1 += extractedCharacter[i] * extractedCharacter[i];
mag2 += storedCharacter[i] * storedCharacter[i];
corr += extractedCharacter[i] * storedCharacter[i];
} // for
corr /= Math.sqrt(mag1*mag2);
return corr;
}
The number of extractedCharacters are around 100-150 per image but the database has 15600 stored binary characters. Checking the coefficient correlation between every extracted character and every stored character has an impact on the performance as it needs around 15-20 seconds to complete for every image, with an Intel i5 CPU.
Is there a way to improve the speed of this program, or suggesting another path of building this bringing similar results. (The results produced by comparing every character with such a large dataset is quite good).
Thank you in advance
UPDATE 1
public static void run() {
ArrayList<byte []> storedCharacters, extractedCharacters;
storedCharacters = load_all_characters_from_database();
extractedCharacters = extract_characters_from_image();
// Calculate the coefficent between every extracted character
// and every character in database.
computeNorms(charComps, extractedCharacters);
double maxCorr = -1;
for(byte [] extractedCharacter : extractedCharacters)
for(byte [] storedCharacter : storedCharactes)
{
corr = findCorrelation(extractedCharacter, storedCharacter)
if (corr > maxCorr)
maxCorr = corr;
}
}
}
private static double[] storedNorms;
private static double[] extractedNorms;
// Correlation between to binary images
public static double findCorrelation(byte[] arr1, byte[] arr2, int strCharIndex, int extCharNo){
final int dotProduct = dotProduct(arr1, arr2);
final double corr = dotProduct * storedNorms[strCharIndex] * extractedNorms[extCharNo];
return corr;
}
public static void computeNorms(ArrayList<byte[]> storedCharacters, ArrayList<byte[]> extractedCharacters) {
storedNorms = computeInvNorms(storedCharacters);
extractedNorms = computeInvNorms(extractedCharacters);
}
private static double[] computeInvNorms(List<byte []> a) {
final double[] result = new double[a.size()];
for (int i=0; i < result.length; ++i)
result[i] = 1 / Math.sqrt(dotProduct(a.get(i), a.get(i)));
return result;
}
private static int dotProduct(byte[] arr1, byte[] arr2) {
int dotProduct = 0;
for(int i = 0; i< arr1.length; i++)
dotProduct += arr1[i] * arr2[i];
return dotProduct;
}
Nowadays, it's hard to find a CPU with a single core (even in mobiles). As the tasks are nicely separated, you can do it with a few lines only. So I'd go for it, though the gain is limited.
In case you really mean cross-correlation, then a transform like DFT or DCT could help. They surely do for big images, but with yours 12x16, I'm not sure.
Maybe you mean just a dot product? And maybe you should tell us?
Note that you actually don't need to compute the correlation, most of the time you only need is find out if it's bigger than a threshold:
corr = findCorrelation(extractedCharacter, storedCharacter)
..... more code to check if this is the best match ......
This may lead to some optimizations or not, depending on how the images look like.
Note also that a simple low level optimization can give you nearly a factor of 4 as in this question of mine. Maybe you really should tell us what you're doing?
UPDATE 1
I guess that due to the computation of three products in the loop, there's enough instruction level parallelism, so a manual loop unrolling like in my above question is not necessary.
However, I see that those three products get computed some 100 * 15600 times, while only one of them depends on both extractedCharacter and storedCharacter. So you can compute
100 + 15600 + 100 * 15600
dot products instead of
3 * 100 * 15600
This way you may get a factor of three pretty easily.
Or not. After this step there's a single sum computed in the relevant step and the problem linked above applies. And so does its solution (unrolling manually).
Factor 5.2
While byte[] is nicely compact, the computation involves extending them to ints, which costs some time as my benchmark shows. Converting the byte[]s to int[]s before all the correlations gets computed saves time. Even better is to make use of the fact that this conversion for storedCharacters can be done beforehand.
Manual loop unrolling twice helps but unrolling more doesn't.

Binomial coefficient in Java (adapting the following source)

I have 2 parameters and I want the method to return an int result.. I was given this code but I don't understand naff all about binoms etc and don't know how to "convert" it
has double BC[126][126]; defined somewhere above it. But i don't need that i just want a result for these n and m. (I probably sound like numpty for putting like that)
private void binom(int n, int m) {
int i, j;
if (n>=0)
if (m>n||m<0) System.err.println("Illegal m!!\n");
else {
for(i=0;i<=n;i++) BC[i][0] = 1;
for(i=1;i<=m;i++) BC[0][i] = 0;
for(j=1;j<=m;j++) for(i=1;i<=n;i++)
BC[i][j] = BC[i-1][j-1] + BC[i-1][j];
}
else System.err.println("Negative n!!\n");
}
You could just return BC[n][m] which is the element you calculate with the three for cycles..
by the way you have at least three possible implementations:
trivial recursive
this one (dynamic programming)
using the formula n! / (n-m)!m! which is no good since fact operations are annoying
A correction: your approach would be dynamic programming if you avoid to recalculate all the coefficients everytime the method gets invoked but it is not your case..
See the article Computing Binomial Coefficients for an example with comparable complexity, O(n2), but using only O(n) space instead of O(n2).

Categories