In old C, what does this mean? double (*Window)(double) - java

I am trying to convert some old DSP code written in C into Java and later to C#. I do not understand what the argument "double (*Window)(double)" means and how to reference it in the Java code. The following function has me unsure what to do.
void WinFirI(float LowOmega, float UppOmega,
float *Shape, int Len, double (*Window)(double), float shift)
{ int i; double time,phase,shape;
// printf("WinFirI: %5.3f %5.3f %d\n",LowOmega,UppOmega,Len);
for(i=0; i<Len; i++)
{ time=i+(1.0-shift)-(float)Len/2; phase=2*M_PI*time/Len;
if(time==0) shape=UppOmega-LowOmega;
else shape=(sin(UppOmega*time)-sin(LowOmega*time))/time;
// printf("%2d %5.1f %5.2f %7.4f %7.4f\n",i,time,phase,shape,(*Window) (phase));
Shape[i]=shape*(*Window)(phase)/M_PI; }
}
So far I have written this:
public void WinFirI(float LowOmega, float UppOmega,
float[] Shape, int Len, double[] Window, float shift) {
double time;
double phase;
double shape;
// printf("WinFirI: %5.3f %5.3f %d\n",LowOmega,UppOmega,Len);
for(int i=0; i<Len; i++) {
time = i +(1.0-shift) - (float)Len/2;
phase = 2 * Math.PI * time / Len;
if(time==0) {
shape = UppOmega - LowOmega;
}
else {
shape=(Math.sin(UppOmega*time) - Math.sin(LowOmega*time)) / time;
}
// printf("%2d %5.1f %5.2f %7.4f %7.4f\n",i,time,phase,shape, (*Window)(phase));
//Shape[i]=shape*(*Window)(phase)/M_PI;
Shape[i] = shape * Window[phase]/Math.PI;
}
}

Pointer to function with parameter double returning double.

As an added note, implementing this function pointer behavior in Java would be done through an anonymous class/interface.
double Window(double param);
In Java would be:
interface WindowFnWrapper {
double Window(double param);
}
Then the function signature would be:
public void WinFirI(float LowOmega, float UppOmega,
float[] Shape, int Len, WindowFnWrapper WindowWrapper, float shift)
Every time you call Window() you would replace it with WindowWrapper.Window().

The declaration double (*Window)(double) declares a parameter Window, whose value is a pointer to a function. That function must be one which takes a single double as an argument, and returns a double.
In your C code, (well, actually the commented-out part), that pointer gets dereferenced, and the function called, passing phase as its argument. That is, the value of the expression (*Window) (phase) is just the result of calling the function whose address you passed in.
If you're using Java 8 or above, the nearest available equivalent is the Function generic class, from the java.util.function package. So if you write
import java.util.function.Function;
then you can declare the parameter as
Function<Double,Double> window
and use it as
window.apply(phase);
The only real difference between this and your C code is that the type parameters to Java generics can't be primitive types such as double.
Double is a reference type that works a bit like double, except that a Double can be null, whereas a double can't. In effect, this should make no difference to your code, except that you may want to add some error handling to deal with the case where window.apply(phase) evaluates to null.

Related

How to calculate area with two variable using a function?

i m solving this question in order to calculate area with answer of double and int.it didnt work, whats wrong with code?
i try to include double radius and int radius inside, it showed cannot be applied to given types.
public static void main(String args[]){
for (int radius = 0; radius < 5 ; radius++)
PrintArea(radius);
for (double radius = 0; radius < 2.6 ; radius+= 0.5)
PrintArea(radius);
}
public static void PrintArea(int radius,double radius){
double area=3.142*radius*radius;
System.out.println(area);
}
i expect it could be calculated and shows answer in double ,but it shows error.
One thing, you should not use the same name for two parameters of a function.
So PrintArea(int radius, double radius) is incorrect and is probably one of the errors you're getting.
The other one, is that you are calling PrintArea with only one parameter, when it expects two.
Rename your parameters int r1 and double r2 instead, like so:
public static void PrintArea(int r1,double r2){
double area=3.142*radius*radius;
System.out.println(area);
}
Or use a PrintArea with only one parameter, of type double:
public static void PrintArea(double radius){
double area=3.142*radius*radius;
System.out.println(area);
}
There are certain issues with your code, your printArea function accepts two arguments, but you are sending only
one while calling the function. Your printArea function needs only one parameter radius (no need of two parameters). The other issue is
that within your printArea function, the data type of parameter is of type int. So when you call this
function with different parameter other than int, it will throw error, as you are calling the function printArea with parameters of type double in your second for loop.
There's a few things going on that can be cleaned up. First of all, why does the PrintArea function need 2 parameters? You call it with only one, and just thinking generally, we don't need two pieces of information to get the area of a circle. So I'm going to guess that you meant only one parameter.
public static void PrintArea(double radius){
double area=3.142*radius*radius;
System.out.println(area);
}
Which will work for both int and double types. Usually we also use camelCase in Java, which means that for methods like "PrintArea" which is made up of multiple words, the first word starts with a lowercase letter, and every other word after that starts with an uppercase letter.

Meaning of `x+" "+y` and `changeUs(x, y)`

I've got this code and i have got the answer for it as well, but I don't understand how they come out like that, specifically what does (x+" "+y) part means as well as the changeUs(x, y), can anyone explain?
public class ChangeParam {
public static void main(String[] args) {
int x = 1;
double y = 3.4;
System.out.println(x+" "+y);
changeUs(x, y);
System.out.println(x+" "+y);
}
public static void changeUs(int x, double y) {
x = 0;
y = 0.0;
System.out.println(x +" "+y);
}
}
The answers are:
1 3.4
0 0.0
1 3.4
This is logic, because Java pass by value and not by reference.
When you call changeUs(x, y) the the x and y will change only in the method, for that you get this result.
public static void main(String[] args) {
int x = 1;
double y = 3.4;
System.out.println(x+" "+y);//<<-------- 1- This will print 1 3.4
changeUs(x, y);
System.out.println(x+" "+y);//<<-------- 3- This will print 1 3.4
}
public static void changeUs(int x, double y) {
x = 0;
y = 0.0;
System.out.println(x +" "+y);//<<-------- 2- This will print 0 0.0
}
You should read and study the Tutorial and the Java Language Specification. The semantics of operators such as + are among the first things explained. There you'll find that when either operand of + is of type String that the other operand is converted to a String via an implicit call to String.valueOf, making the whole expression a String concatenation.
System.out.println() - here, println is a method which takes in a String type as argument (either a String, or a type which has been converted to a String).
So , we pass a String. But, you've two things to display (x and y), how will you do that?
In java, '+' operator acts as a concatenation operator when operands are String type, so x+" "+y will combine 'x' and 'y' with a space in between.
So, if x="HELLO" and y="WORLD" , so x+y will be HELLOWORLD.
Giving a space in between, x+" "+y will give us a cleaner and more readable answer: HELLO WORLD
where as
changeUS()
is a method (specifically a static method) which takes in two parameters (much like a math function which needs two parameters).
So, we pass two "things" to the function. Now, how do I know the function needs two parameters? To know that I must know where the function is defined. As I see, the function is defined as:
public static void changeUs(int x, double y) {
x = 0;
y = 0.0;
System.out.println(x +" "+y);}
The first line: enter code here:public static void changeUs(int x, double y)which says that changeUs takesint and double` as their parameters.
So, pass an integer and a floating point number (double is a higher precision floating point number) .
But, why did we do System.out.println but for changeUs we just called it without any of that prefixes?
This is because changeUs is a 'static' method and doesn't need an object to operate upon.

Java Casting in Method Overloading

I have the methods overloading such as:
public int sum1(int a, int b)
{
int c= a+b;
System.out.println("The method1");
return c;
}
public float sum1(int a, float b)
{
float c= a+b;
System.out.println("The method2");
return c;
}
public double sum1(float a, float b)
{
double c= (double) a+b;
System.out.println("The method3");
return c;
}
From the main method, suppose we have
double x=10.10f;
double y=10.20f;
the apparent type for x and y is double, but the actual type is float. when I call
System.out.println(" the output is :"+cc.sum1(x,y));
the error in the compile-time.
The method sum1(int, int) in the type Class is not applicable for the arguments double, double).
where it should go to sum1 (i.e. method3) by casting double to float
TL;DR version of this answer:
Variables of primitive types never have a different type at execution-time to their compile-time. (A double is always a double, never a float, etc.)
Overload resolution (picking which method signature is used) is performed using the compile-time types of expressions
Method implementation of the picked signature is performed using the execution-time type of the target of the method call
the apparent type for x and y is double, but the actual type is float
No, it's not. You've just got a conversion from the assigned float literals to double values. The actual values are double.
Primitives don't work like objects - there's no idea of an int value still being an int inside a double variable, for example.
It's simpler to take an example with integer types. Suppose we have:
byte b = 100;
int x = b;
The value of x is the 32-bit integer representing the value 100. It doesn't "know" that it was originally assigned from a byte value... there just happened to be a conversion from byte to int at the point of assignment.
Compare that with reference types:
String x = "hello";
Object y = x;
Here, the value of y really is a reference to a String object. That type information is preserved precisely because there's a whole object that can contain it, and because the value of the variable itself is only a reference. (The bits themselves don't need to change as part of the assignment - in a simple VM at least, they'll be the exact same bits in x and y, because they're referring to the same object.)
Even in that case, however, overload resolution occurs based on the compile-time type of the arguments, not their actual values at execution time. The only way that the execution-time type of a variable gets involved is with overriding based on the target of a method call. So if we have:
Foo f = new X();
Foo g = new Y();
Foo h = new Z();
f.someMethod(g, h);
... then the compiler will look for a method in Foo which has two Foo parameters (or Object or other superclasses/interfaces) - the actual types of the objects involved are irrelevant. At execution time, however, if that method has been overridden in X, then that override will be called due to the execution-time type of the object f's value refers to.
Casting double to float may cause loss of data, since it's a narrowing conversion, and is therefore not done automatically by the compiler. You'll have to cast the variables to float explicitly if you want it to take place.
No, the actual type of the variables is double. The type of the constants that you're assigning to that double variable, which get promoted on assignment, is float.
Try to add new function: public double sum1(double a, double b). It will solve your problem.
And also, this kind of casting will cause loss of data.
Floats are funny that way.. they always try to convert to doubles automatically. This code compiles, with floats at every turn.
public class wood {
public static void main(String[] args) {
float x = 10.1f;
float y = 10.2f;
System.out.println("Sum of x and y = " + sum1((float)x, (float)y));
}
public static float sum1(float x, float y) {
return (float)((float)x+(float)y);
}
}
edit; note that using a cast operator outside of parenthesis will cast after what is inside of the parenthesis has computed. So;
System.out.println((int)(50.5 + 50.7));
will print out 101.
Within java, some data conversions are automatic, and others require cast operators.. simply put, java will automatically make widening conversions, while you will have to use a cast operator for narrowing conversions.
The hierarchy of primitive data types is as follows:
byte //1 byte (-128 through 127)
short //2 bytes (over 32,000 give/take from 0)
int //4 bytes (over 2billion give/take from 0)
long //8 bytes (over 9 quintillion (10^18) give/take from 0)
float //4 bytes (holds 7 decimal places)
double //8 bytes (holds 15 decimal places)
java will not make narrowing conversions automatically, because then data is at risk of being lost. Both byte and short will become ints automatically.
short s = 5;
byte b = 5;
short sum = s + b; //this will cause an error!
s and b automatically make a widening conversion to an int, and an int cannot be assigned to a short without a cast operator.
short sum = (short)(s + b);
would be needed.

java compare to from double to int tostring method

How do i go about using compareto for a double and i want to turn it into an int?
An example would be nice. I have been searching the java api.
also is it possible to use if and else statements with a String toString method? Mine has kept on crashing for special cases.
im a total noob to java i guess i been reading constantly to learn
If you want to compare an integer with a double you will need to convert the integer to a double. Please be aware that this won't work the other way round as an int couldn't hold all the values a double can: Values will be round down
double d = 12.3;
return (int)d;
will return 12! and doubles can hold values way bigger and small than int could
double d = 1.337E42
return (int)d;
returns 2147483647! There are many orders of magnitude in between. So please always convert the int to a double to prevent this to happen.
You can use following code for comparison:
int compare(double d, int i) {
return new Double(d).compareTo(new Double(i));
}
But keep in mind that Double differs from double as Double is an object and not a primitive type, so there will be more overhead when handling a Double compared to using a double or int.
As for the second part of your question I don't really understand what's your question/intention. Please try to clarify it.
you can try something like this
Double d = 10.0;
Integer i = 10;
d.compareTo(i.doubleValue());
or
i.compareTo(d.intValue());
I'm not sure which one you need.
You do not want to convert to String because that would compare the numbers lexicographically rather than numerically.
I will take your question to mean, "How do I create a compareTo() method for doubles?"
I also think you are using this to implement a data structure for doubles.
Here is how I would go about it.
When you construct a data structure, you will construct it as a Double object.
Double is a built-in class in java.lang package that boxes the double primitive.
Then, java will automatically cast them to that type.
The reason you want to use the Double class as the defining type for your data structure is so that you can use its built-in compareTo method. There is no way to make the primitive data type double contain the compareTo method.
Here is some code to help you get started for example:
TreeMap <Double, String> myDoubleMap = new TreeMap <Double, String> (10);
for (int i = 0; i < 10; i++)
myDoubleMap.put ( Math.sqrt( 10.0 * i) , "" + i);
System.out.println(myDoubleMap);
(Make sure you import java.util.TreeMap if you are to run this example)
I can only guess at your exact requirements. You should try to refine them a little more clearly.
If you want to compare doubles and ints, it may be tough. You have two options.
one: cast the double to an int, and compare
int compare(double d, int i) {
int dint = (int)d;
return Integer.compare(dint,i);
}
int compare(int i, double d) {
int dint = (int)d;
return Integer.compare(i,dint);
}
two: cast the int to a double, and compare
int compare(double d, int i) {
double idouble = (double)i;
return Double.compare(d,idouble);
}
int compare(int i, double d) {
double idouble = (double)i;
return Double.compare(d,idouble);
}

Java: calculating area of a triangle

import java.lang.Math;
import java.awt.*
public class Triangle implements Shape
{
java.awt.Point a;
java.awt.Point b;
java.awt.Point c;
public Triangle(java.awt.Point a, java.awt.Point b, java.awt.Point c)
{
this.a = a;
this.b = b;
this.c = c;
}
public double getArea( )
{
double area;
return area = Math.abs((a-c)*(b-a)-(a-b)*(c-a));
} ...
http://upload.wikimedia.org/math/f/e/5/fe56529cdaaaa9bb2f71c1ad8a1a454f.png <--area formula
I am trying to calculate the area of a triangle from 3 points (x,y) from a 2D Cartesian coordinate system. I'm assuming that my above formula correctly yields the area of a triangle (if not, please correct me) but my compiler says "operator - cannot be applied to java.awt.Point,java.awt.Point". I'm assuming it's saying this because you cannot subtract points from each other, but each value in the formula is either an x or y value, not a point. How can I fix my code so this would work?
Thanks!
According to Wikipedia, you formula is correct. The article contains lots of useful and clear data.
According to the java.awt.point documentation, you should use the getX() and getY() methods, which return the coordinate value of a point.
That is,
Should be expressed as:
Math.abs((a.getX()-c.getX())*(b.getY()-a.getY())-
(a.getX()-b.getX())*(c.getY()-a.getY()))*0.5;
It is probably not such a good practice to use point.x, because you shouldn't access an object's variable if you have a getter method that does that. This is the one aspect of separation between interface and implementation: the data point.x might be stored in many forms, not just int; The interface method assures that you'll get an int every time you use it.
compiler is telling you the exact right thing.
Math.abs((a-c)*(b-a)-(a-b)*(c-a)
you forgot .x in a.x .y in b.y etc. that is (a.x - c.x)* ...
Update: I didn't notice that OP had linked to a formula, that's why I looked up this one and coded it. You should use the other formula as this one involves more calculations (including 4 calls to sqrt, I think that would be heavy).
Using Heron's formula
double distance(Point a, Point b)
{
double dx = a.x - b.x;
double dy = a.y - b.y;
return Math.sqrt(dx * dx + dy * dy);
}
double getArea()
{
double ab = distance(a, b);
double bc = distance(c, b);
double ca = distance(a, c);
double s = (ab + bc + ca) / 2;
return Math.sqrt(s * (s - ab) * (s - bc) * (s - ca))
}
As the linked formula says, don't calculate with the points but with their x- and y-values. I'll leave it to you (it's homework!) to do that in java.
And don't forget to divide by 2.
Use a.x - c.x etc.
Just read the Javadoc:
http://java.sun.com/j2se/1.5.0/docs/api/java/awt/Point.html
The underlying problem: In Java, operators like '+' and '-' are only allowed for primitive types (like byte, int, long) but not for objects (in general) and arrays.
Other languages allow for operator overloading, so in c++ you could define a '+' operation for Point objects and there your initial idea would compile and run. But that is not possible in Java.
The only exceptions are String (it's allowed to 'add' String objects) and the primitive wrappers like Integer and Double in Java 1.5+ (autoboxing converts them back to primitives)

Categories

Resources