I read the next answer about passing function as parameter.
Still, I don't get the idea. My function can get any function: sin(x), cos(x), etc.
As I understood, I can create an interface, for example:
public interface functionI<T> {
}
that would wrap It.
Now I have my function:
public void needToDo(functionI<Integer> a, int x0Par, int hPar){
}
(needToDo, for example, need to substitue the x of the function n x0par and hPar, and find the Max. If I got sin(x), I need to find the max of sin(x0Par) and (sin(hPar)).
I didn't understand how I use it in my function. How will I know what to do when I got the function, that can be anything (polynomial, sin(x), and so on)
Something like this:
public interface Function1<RESULT,INPUT> {
RESULT call(INPUT input);
}
public class Sin implements Function1<Double,Double> {
public static final Sin instance = new Sin();
private Sin() {
}
public Double call(Double x) {
return Math.sin(x);
}
}
public Double needToDo(Function1<Double,Double> aFunction, Double x0Par, Double hPar) {
Double d1 = aFunction.call(x0Par);
Double d2 = aFunction.call(hPar);
return d1 > d2 ? d1 : d2;
}
public static void main(String[] args) {
Double x0Par = 10.2;
Double hPar = 1.9;
Double ret = needToDo(Sin.instance, x0Par, hPar);
System.out.println(ret);
}
It doesn't quite work like that; you cannot pass arbitrary functions as parameters in Java, instead you pass objects which have specific, often generic sounding, functions.
So you could define a MathOperation interface, which has an execute method, taking a double and returning a double.
public interface MathOperation {
double execute(double x);
}
and then you can create
public class Sin implements MathOperation {
public double execute(double x) { return Math.sin(x); }
}
and have a function that uses it like
public void needToDo(MathOperation op, double x) {
System.out.println(op.execute(x));
}
You could create an on-the-fly function for needToDo like
...
needToDo(new MathOperation() {
public double execute(double x) { return x * 2.0; }
});
...
But you can't pass Math.sin as a parameter. There are reflection tricks you can do, but that's another issue.
Related
I have this code:
public class doubles() {
private Double a;
public Double getA(){
return this.a
}
public void setA(Double a){
this.a = a
}
}
I want the variable 'a' to retain the properties of an integer when I do for instance
**setA(13)**
i.e a=13 and not a=13.0
Still I want variable 'a' to have the properties of a Double when I for instance
**setA(13.32)**
i.e a=13.32
Here is the small code for what you need. Please, bare in mind that I strongly advice not to follow this principle.
public class Example {
private Number a;
public Number getA() {
return a;
}
public void setA(Double a) {
if (a % 1 == 0) {
this.a = a.intValue();
} else {
this.a = a;
}
}
public void setA(int a) {
this.a = a;
}
public static void main(String[] args) {
double integerNumber = 6;
Example example = new Example();
example.setA(integerNumber);
System.out.println(example.getA());
}
}
Alternatively to using the base class Number proposed in the other answer, one can use BigDecimal: a class which stores the precision / decimal places. Hence 3.10 * 2.00 = 6.2000.
new BigDecimal("3.10").multiply(new BigDecimal("2.00"))
Disadvantage: the awkward verbosity.
Advantage: precision (called scale) and does not have the approximation errors of floating point: 3.1 = 3.100 = actually 3.099999871...
I don't understand how to make two doubles as input and return the biggest number.
Make a new function (method) that takes two doubles as input and return the biggest one.
My solution (trying an if-statement):
public class ex1DoubleFunction {
public static void main(String[] args) {
double a = 10;
double b = 20;
System.out.println(doublefun(a, b));
public static doublefun(a,b) {
if (a>b) {
return a;
}
else if (a<b) {
return b;
}
}
}
}
This is also consider if you have equals value.
public static double whichGreater(double first, double second) {
if(first >= second){
return first;
} else {
return second;
}
}
This is a very simple task, the solution below should do.
public static double findMax(double numOne, double numTwo){ // parameters
return Math.max(numOne,numTwo); // built in class to find the max of two nums or more
}
Also, make sure you don't put this function inside the main method because it won't work. put this inside the same class as the main method for simplicity.
This should work.
public static double doublefun(double a, double b) {
if ( a > b) {
return a;
} else {
return b;
}
}
You can also use ternary operator.
return (a>b)?a:b;
For my assignment, I have been asked to create a test harness which provides feedback on whether the following sums are true. For this question, I will only provide one sum as an example. I have been asked to produce the following:
TestCalculator has a method called testParser() which:
Tests that x("12 + 5") returns a Double with the value 17
I have been given a template in which to set this out on which looks like this:
Template
public class TestCalculator {
Double x;
/*
* Adds the parameter x to the instance variable x and returns the answer as a Double.
*/
public Double x(Double x){
System.out.println("== Adding ==");
//Sum here
return new Double(0);
}
public void testParsing() {
if (//condition) == 17) {
System.out.println("Adding Success");}
else {
System.out.println("Adding Fail");
}
}
And this is what I've managed to come up with so far:
Current program...Main class
public class Main {
public static void main(String[] args) {
TestCalculator call = new TestCalculator();
call.testParsing();
}
}
TestCalculator class
public class TestCalculator {
Double x;
Double doubleObject = 1.0;
/*
* Adds the parameter x to the instance variable x and returns the answer as a Double.
*/
public Double x(Double x){
System.out.println("== Adding ==");
this.x = 12.0;
x = 5.0;
return new Double(0);
}
public void testParsing() {
if (x(doubleObject) == 17) {
System.out.println("Adding Success");}
else {
System.out.println("Adding Fail");
}
}
}
I have two main queries. Firstly, I have been asked to test if "x("12 + 5") returns a Double with the value 17". I can see that this has been laid out so that the sum is a data type of String and I am confused as to why or how you would perform this calculation using the string data type.
Secondly, Within my current version of the program, the output returns that the adding calculation failed because I cannot access the returned double value of the calculation. But I am unsure of how I would access that value in my if statement and also return the output of the calculation and put it into the Double value that is returned in the method.
I have tried to make the question as clear and concise as possible for the reader to understand, any help on this would be greatly appreciated, thanks.
to return a new value that adds two values consider
public Double x(Double x){
System.out.println("== Adding ==");
//Sum here
this.x = x;
return new Double(x + 5);
}
Called as
if (x(12.0) == 17.0) {
Do you see anything wrong in this code? in thosen't work well it returns a NaN.
public class Method2 extends GUIct1
{
double x=0,y=0;
void settype1 (double conv1)
{
x = conv1;
}
void settype2 (double conv2)
{
y = conv2;
}
double conversion ( double amount)
{
double converted = (amount*y)/x;
return converted;
}
}
Way it is used an i already changed the set part
Method2 convert = new Method2(); \\ method is called
.....
convert.settype1(j);
.....
convert.settype2(k);
.....
double x = convert.conversion(i);
System.out.println(x);
Well, the fact that you've got methods which set variables called get-something is pretty obviously not a good idea, and there's no indentation... but it should work. But then, you haven't shown how you're using it. Perhaps you're not actually called the setter methods?
Here's an example of the same code but with different names, and a sample of using it:
class Converter
{
double multiplier = 0;
double divisor = 0;
void setMultiplier(double multiplier)
{
this.multiplier = multiplier;
}
void setDivisor(double divisor)
{
this.divisor = divisor;
}
double convert(double amount)
{
return (amount * multiplier) / divisor;
}
}
public class Test
{
public static void main(String[] args)
{
Converter converter = new Converter();
converter.setMultiplier(3.5);
converter.setDivisor(8.5);
System.out.println(converter.convert(2)); // Prints 0.8235294117647058
}
}
Personally I'd probably make the variables final and set them in the constructor, but that's another matter...
It doesn't look like you ever call gettype1 or gettype2 so the x/y is 0/0 resulting in NaN
This can happen when x=0. Division by zero is not defined. Print out x and y before you start to calculate to see whetther they are not zero.
Im trying to to create a simple 4 function calculator using a jump table without switch case or if/else statements. I understand I can create the jump table via function pointers but I am kindda blanking out. I've started with the addition and subtraction part of the program but am trying to grasp the design/strategy to use. I am also getting an error when putting the method in the array, so far this is what i have:
public class Calculator {
public abstract class Functor{
abstract double Compute(double op1, double op2);
}
class Addition extends Functor
{
public double Compute(double op1, double op2){ return op1 + op2;}
}
class Subtraction extends Functor
{
public double Compute(double op1, double op2){ return op1 - op2;}
}
public static void main(String[] args) {
Functor add = new Addition(); // Problem here
Functor sub = new Subtraction(); // and here
}
}
any help or ideas for the step in the right direction is greatly appreciated!
thanks in advance!
Let's try this instead:
public enum Operation {
PLUS("+") {
double apply(double x, double y) { return x + y; }
},
MINUS("-") {
double apply(double x, double y) { return x - y; }
},
TIMES("*") {
double apply(double x, double y) { return x * y; }
},
DIVIDE("/") {
double apply(double x, double y) { return x / y; }
};
private final String symbol;
Operation(String symbol) {
this.symbol = symbol;
}
#Override public String toString() {
return symbol;
}
abstract double apply(double x, double y);
}
This will only work if you're using Java 5 or later, which has generics and enums. What this does is it gives you a static set of operations. You access them by typing Operation.PLUS or Operation.MINUS, etc.
To test it try this:
public static void main(String[] args) {
double x = Double.parseDouble(args[0]);
double y = Double.parseDouble(args[1]);
for (Operation op : Operation.values())
System.out.printf("%f %s %f = %f%n", x, op, y, op.apply(x, y));
}
For more information consult Effective Java, Second Edition by Joshua Bloch.
It's worth pointing out that Java has no notion of "function pointers". Rather you simple write an interface and write a class that implements that interface. The correct class to use is selected at runtime; hence, that is a "jump table" but it's hidden behind the semantics of object-oriented programming. This is known as polymorphism.
While that's decent (aside from not having constructors that work right) I'd do it different, using anonymous classes.
abstract class Functor {
public abstract double compute(double a, double b);
public static void main(String[] args) {
Functor add = new Functor() {
// defining it here is essentially how you do a function pointer
public double compute(double a, double b) { return a + b; }
};
Functor subtract = new Functor() {
public double compute(double a, double b) { return a - b; }
};
System.out.println(add.compute(1.0,2.0));
System.out.println(subtract.compute(1.0,2.0));
}
}
Result:
C:\Documents and Settings\glowcoder\My Documents>java Functor
3.0
-1.0
C:\Documents and Settings\glowcoder\My Documents>
You don't have any constructors to pass in any arguments to your sub-classes, I don't understand how you think opt1 and opt2 are going to be set without any constructors with those as parameters. This is not correct Java code right now.