Workaround for passing a method into a method? - java

I am looking for a way to pass a method as a parameter into another method.
I am currently trying to simulate the Newton's-method (http://en.wikipedia.org/wiki/Newton%27s_method) in Java with the following code:
public class Newton {
// Iterationmethod
public void newtonCalc(double x0) {
double x;
// counter
int i = 0;
//Newton-Iteration for x0
x = x0 - (y2(x0) / y2Deriv(x0));
while (Math.sqrt(y2(x)*y2(x)) >= Math.pow(10, -10)){
//Newton-Iteration x(n+1)
x = x - (y2(x))/ y2Deriv(x);
i++;
System.out.printf("%d. %.11f\n",i,y2(x));
}
System.out.printf("%d steps were necessary for a resolution of 10^-10", i);
}
// Function for (2)
public static double y2(double x) {
return Math.sin(x) / (1 - Math.tan(x));
}
// Derivative for (2)
public static double y2Deriv(double x) {
return (Math.cos(x) + Math.sin(x) * Math.tan(x) * Math.tan(x))
/ ((Math.tan(x) - 1) * (Math.tan(x) - 1));
}
// Function for (4)
public static double y4(double x) {
return Math.exp(-1/Math.sqrt(x));
}
// Derivative for (4)
public static double y4Deriv(double x) {
return Math.exp(-1/Math.sqrt(x))/(2*Math.pow(x, 3d/2));
}
public static void main(String[] args) {
Newton newton = new Newton();
newton.newtonCalc(1);
}
}
newtonCalc(x0) gets an x0 at wich the iteration should be started.
But the function (y2) now is hardcoded into this method. I want it to be flexible.
For example newtonCalc(double x0, Method y) to run the iteration for y starting at x0.
I have 2 different functions (y2 and y4 which are both functions from a excercise sheet from my lecture plus its derivatives y2Deriv and y4Deriv which are used in the Iterationmethod).
I know passing a method is not possible but i dont get any easy workaround.
Forgive me if this is unclear or i have missed any necessary information!
Regards,
Tak3r07

It's entirely possible since Java 8, using lambda expressions

If you want to stay with pre-Java-8 methods, make an interface Function with member functions eval and deriv and pass (possibly anonymous) instances of derived classes to the Newton class invocation.
This could look like (I'm not sure that all details are correct, these are just code fragments to illustrate the idea)
interface Function {
public double eval(double x);
public double deriv(double);
}
class Example1 implements Function {
#override
public double eval(double x) { return x*(x+3)+1; }
#override
public double deriv(double) { return 2*x+3; }
}
....
Solver solver1 = new Newton(new Example1(),x0);
....
Solver solver2 = new Newton(new Function(){
#override
public double eval(double x) { return cos(x); }
#override
public double deriv(double) { return -sin(x); }
}, x0);

Related

LuaJ Vector Class

I am trying to create a Vector class for use with LuaJ. The end goal is to have the user not write much lua, and have most of the work done on my Java engine.
As my understanding goes, I need to set the metatable for the lua representation of my Java vector class? The problem I am having though, is that when I am trying to overwrite some metatable functionality it doesn't seem to have any affect in my lua script. What I am trying to do now is overwrite the + operator, so I can add two vectors together or add a vector by a constant.
Here is my Vector class so far:
package math;
import org.luaj.vm2.*;
import org.luaj.vm2.lib.*;
import org.luaj.vm2.lib.jse.*;
public class Vector3Lua {
public float X;
public float Y;
public float Z;
public Vector3Lua unit;
static {
// Setup Vector class
LuaValue vectorClass = CoerceJavaToLua.coerce(Vector3Lua.class);
// Metatable stuff
LuaTable t = new LuaTable();
t.set("__add", new TwoArgFunction() {
public LuaValue call(LuaValue x, LuaValue y) {
System.out.println("TEST1: " + x);
System.out.println("TEST2: " + y);
return x;
}
});
t.set("__index", t);
vectorClass.setmetatable(t);
// Bind "Vector3" to our class
luaj.globals.set("Vector3", vectorClass);
}
public Vector3Lua() {
// Empty
}
// Java constructor
public Vector3Lua(float X, float Y, float Z) {
this.X = X;
this.Y = Y;
this.Z = Z;
this.unit = new Vector3Lua(); // TODO Make this automatically calculate
System.out.println("HELLO");
}
// Lua constructor
static public class New extends ThreeArgFunction {
#Override
public LuaValue call(LuaValue arg0, LuaValue arg1, LuaValue arg2) {
return CoerceJavaToLua.coerce(new Vector3Lua(arg0.tofloat(), arg1.tofloat(), arg2.tofloat()));
}
}
// Lua Function - Dot Product
public float Dot(Vector3Lua other) {
if ( other == null ) {
return 0;
}
return X * other.X + Y * other.Y + Z * other.Z;
}
// Lua Function - Cross Product
public LuaValue Cross(Vector3Lua other) {
Vector3Lua result = new Vector3Lua( Y * other.Z - Z * other.Y,
Z * other.X - X * other.Z,
X * other.Y - Y * other.X );
return CoerceJavaToLua.coerce(result);
}
}
Here is the lua script that makes use of this:
local test1 = Vector3.new(2, 3, 4);
local test2 = Vector3.new(1, 2, 3);
print(test1);
print(test2);
print(test1+2);
The last line produces an error, as it says I cannot add a userdata and a number together. However, in my vector class I tried to get it to just print what is being added, and just return the original data (to test). So I believe my problem is how I am defining my metatable; In my vector class, the two print's are never called.
print(test1+2); should be print(test1+test2);. You got that error because test1 is a userdata (basically an under-the-hood version of a table) and 2 is a number.

Signing up Codewars - Java Exercise

The code is
public class Multiply
{
public static Double multiply(Double a, Double b)
{
return a * b
}
}
I cannot solve the above code.
I tried a few things, like
public class Multiply
{
public double multiply(double a, double b)
{ return a * b;}
}
It still shows errors in code.
Kindly help, please.
You essentially had the answer Codewars wanted. I imagine they expected for you to just add the semicolon, as you did, but keep the rest of the code the same.
public class Multiply
{
public static Double multiply(Double a, Double b)
{
return a * b;
}
}
I went to try it out, and this worked for me. Looks like they wanted you to keep static and the wrapper class Double.
Here is the answer:
public class Multiply
{
public double multiply(double a, double b)
{ return a * b;}
}
Think about how it will work if it is executed without any main method and what all things are missing / incorrect format in the code
E.g. Where you can add any double value
public class Multiply {
public static double multiply(double a, double b) {
return a * b;
}
public static void main(String[] args) {
double result = multiply(20.01, 10.10);
System.out.println("The result is: " + result);
}
}
public class Multiply {
public double multiply(double a , double b )
//just change the wrapper to primitive
{
return a*b ;
// add semicolon over here that it
}

Java Interfaces/Callbacks for Using 1 of 2 Possible Methods

I have read up on Java Interfaces (callbacks) because I was told by a professor I should use callbacks in one of my programs. In my code, there are two Mathematical functions I can 'pick' from. Instead of making a method activate() and changing the code inside (from one function to the other) when I want to change functions, he said I should use callbacks. However, from what I've read about callbacks, I'm not sure how this would be useful.
EDIT: added my code
public interface
//the Interface
Activation {
double activate(Object anObject);
}
//one of the methods
public void sigmoid(double x)
{
1 / (1 + Math.exp(-x));
}
//other method
public void htan(final double[] x, final int start,
final int size) {
for (int i = start; i < start + size; i++) {
x[i] = Math.tanh(x[i]);
}
}
public double derivativeFunction(final double x) {
return (1.0 - x * x);
}
}
If you want to use interfaces something like this would work.
I have a MathFunc interface that has a calc method.
In the program I have a MathFunc for mutliplication and one for addition.
With the method chooseFunc you can choose one of both and with doCalc the current chosen MathFunc will do the calculation.
public interface MathFunc {
int calc(int a, int b);
}
and you can use it like that:
public class Program {
private MathFunc mult = new MathFunc() {
public int calc(int a, int b) {
return a*b;
}
};
private MathFunc add = new MathFunc() {
public int calc(int a, int b) {
return a+b;
}
};
private MathFunc current = null;
// Here you choose the function
// It doesnt matter in which way you choose the function.
public void chooseFunc(String func) {
if ("mult".equals(func))
current = mult;
if ("add".equals(func))
current = add;
}
// here you calculate with the chosen function
public int doCalc(int a, int b) {
if (current != null)
return current.calc(a, b);
return 0;
}
public static void main(String[] args) {
Program program = new Program();
program.chooseFunc("mult");
System.out.println(program.doCalc(3, 3)); // prints 9
program.chooseFunc("add");
System.out.println(program.doCalc(3, 3)); // prints 6
}
}

Java generics - accept float and int

How can I program my class to accept both Integers and Floats, I suppose I'll need to use generics, am I correct?
public class Vec2 {
private int x, y;
public Vec2(int xa, int ya) {
this.x = xa;
this.y = ya;
}
public Vec2() {
this(0, 0);
}
public Vec2(Vec2 vec) {
this(vec.x, vec.y);
}
public void addX(int xa) {
x+=xa; // I get an exception here when I try to use generics.
}
public void addY(int ya) {
y+=ya; // I get an exception here when I try to use generics.
}
Any ideas how to program my class to accept floats, integers and doubles altogether?
For the time being, we cannot have generics over primitives like int or double, so you will be forced to use boxed representations. It really is easier to just make a separate class for int and double. But if you want to use generics, here's how you can do it in a type-safe way (using java8):
public class Vec2<T> {
private final BinaryOperator<T> adder;
private T x, y;
private Vec2(BinaryOperator<T> adder, T x, T y) {
this.adder = adder;
this.x = x;
this.y = y;
}
public void addX(T xa) {
x = adder.apply(x, xa);
}
public void addY(T ya) {
y = adder.apply(y, ya);
}
public static Vec2<Integer> ofInt(Integer x, Integer y) {
return new Vec2<>(Integer::sum, x, y);
}
public static Vec2<Double> ofDouble(Double x, Double y) {
return new Vec2<>(Double::sum, x, y);
}
}
Vec2<Integer> intvec = Vec2.ofInt(5, 3);
intvec.addX(8);
Vec2<Double> dblvec = Vec2.ofDouble(5.2, 8.9);
dblvec.addY(-.9);
You could use BigDecimal to back your Vec2 and then you could use create addX and addY method(s) for long and double fairly easily. Something like,
public class Vec2 {
private BigDecimal x, y;
public Vec2(double xa, double ya) {
this.x = BigDecimal.valueOf(xa);
this.y = BigDecimal.valueOf(ya);
}
public Vec2(long xa, long ya) {
this.x = BigDecimal.valueOf(xa);
this.y = BigDecimal.valueOf(ya);
}
public Vec2(Vec2 vec) {
this.x = vec.x;
this.y = vec.y;
}
public void addX(double xa) {
x = x.add(BigDecimal.valueOf(xa));
}
public void addX(long xa) {
x = x.add(BigDecimal.valueOf(xa));
}
public void addY(double ya) {
y = y.add(BigDecimal.valueOf(ya));
}
public void addY(long ya) {
y = y.add(BigDecimal.valueOf(ya));
}
#Override
public String toString() {
return String.format("x = %s, y = %s", x.toString(), y.toString());
}
}
No, you don't, merely have your class inherit from Number and use type checking to ensure that values are of the appropriate class, if necessary, e.g.
Class IsraelG99sClass {
Number n;
public Number add(Number n2) {
if (n instanceof Integer && n2 instanceof Integer) {
return new Integer(n.intValue() + n2.intValue());
} else {
return new Double(n.doubleValue() + n2.doubleValue());
}
}
public Number getValue() {
if ((n instanceof Integer) || (n instanceof Float)) {
return n;
} // handle the other case as appropriate
}
}
Floats and ints are very different values with vastly different mins and maxes. I would try using doubles as the data member with overloaded constructors for different variable types instead of generics unless generics are really needed.
Yes, you can use generics and make your x and y attributes of type T.
But you won't be able to just implement the addX and addY in they way you want.
Check these other answers on how to implement a generic number addition, it's not as simple but you should be able to do it that way.
Java Generics and adding numbers together
how to write a generic method for adding numbers
First of all, I'm operating under the assumption that you want x and y to be of varying (generic) type.
For this, you would want:
public class Vec2<E extends Number> {
private E x, y;
public Vec2(E xa, E ya) {
this.x = xa;
this.y = ya;
}
//Not _easily_ possible with generics, as the compiler has no guarantee that
//zero is an acceptable value. Consider some variation of a Factory pattern,
//but this will work. Note that there is an "officially"-unchecked cast warning.
public Vec2() {
super();
final Number zero = 0.0;
this.x = (E)zero;
this.y = (E)zero;
}
public Vec2(Vec2<E> vec) {
this(vec.x, vec.y);
}
public void addX(E xa) {
Number c = x.doubleValue() + xa.doubleValue();
x = (E)c;
}
public void addY(E ya) {
Number c = y.doubleValue() + ya.doubleValue();
x = (E)c;
}
This should work well. While I encourage you to use generics, note that keeping a numeric type (like int, float, or double) as a generic is often not advisable, as they're only similar on the surface. When you dig into the operations of, say, "+", they are radically different dependent on type. You will also have an assortment of unchecked-cast warnings in this code; perhaps I could have rooted them out properly had I the time, but this just goes back to my warning about generic numbers.
You will also notice a few flukes of the language doing this, such as the way that (E)zero works, but (E)(0.0) does not.
By and large, though, generics are a much easier and cleaner way to go about things than inheritance, when it is possible.

Instance Methods: complex numbers

I am currently doing solo text book work for java(not part of a class) and I'm stuck on a question.
Write an instance method modulus for this class that could be called by a statement like
double size = z.modulus(); where z is of type Complex. If z represented the value a + ib,
then the call would set the variable size to the value of |z| = square root(a2 + b2).
What am I doing wrong?
public class complex {
double re;
double im;
complex x;
public static void main(String[] args) {
public complex z = new complex();
{
z.im = In.getDouble();
z.re = In.getDouble();
}
//public complex modulus = (x);
//{
// x.im = z.im * z.im;
// x.re = z.re * z.re;
// return ;
//}
public double size() {
System.out.println(Math.sqrt(x.im+ x.re));
return Math.sqrt(x.im+ x.re);
}
double size = z.modulus();
// {
//}
private double modulus() {
// TODO Auto-generated method stub
x.im = z.im * z.im;
x.re = z.re * z.re;
return 0;
}
}
I made the changes and came out with this but it still doesn't work i put the errors next to the line in which they occur.
public class complex {
double re;
double im;
public complex z = new complex();
{
z.im = In.getDouble();
z.re = In.getDouble();}
public static void main(String[] args) {
private double modulus() { // insert enumIdentifier and body, Syntax error on "double" # expected.
return Math.sqrt( im * im + re * re );
}
double size = z.modulus();
}
}
You don't need to refer to either x or z. You have the right fields in your class to be able to calculate the modulus.
public double modulus() {
return Math.sqrt( im * im + re * re );
}
However, in the code in your question, you seem to be defining your class's methods inside the main method. You can't do that. Close off the definition of one method (with }) before starting the next.

Categories