I am writing a method to identify a polynomial functions from a given sequence of numbers.
public void updateSequence(Term t) {
for (int i = 0; i <= sequence.length; i++) {
sequence[i] = sequence[i] - t(c) * Math.pow(i, t(e));
}
}
I am having some problems with this method. I am unsure how to call a method called getCoefficient from another class called Term which is basically a method containing the following statement
return coefficient;
and then use that in the method above. I need to find the term which is basically coefficient * i ^exponent and then save it back into the sequence to be run through the iteration again.
These are the content of the term class.
public class Term {
term = coefficient * x ^ exponent
private double coefficient;
private int exponent;
public Term(double c, int e) {
coefficient = c;
exponent = e;
}
// returns the coefficient
public double getCoefficient() {
return coefficient;
}
// returns the exponent
public int getExponent() {
return exponent;
}
// returns the term as a String for display
// see the sample file for the layout required
public String display() {
// TODO
String tocompile = "tocompile";
return tocompile;
}
}
Related
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
}
}
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.
I have 3 classes, Node, HiddenLayer, and InputNode class.
My HiddenLayer and InputNode classes are subclasses of the Node class and they would share the output() method from the Node class (polymorphism).
My question is: why is my object returning 0's in the HiddenLayer class?
Attached is my code:
Node.java
public class Node {
protected double number;
public double output(){
return number;
}
}
HiddenLayer.java
public class HiddenLayer extends Node {
protected Node[] input;
public HiddenLayer(Node[] nodes) {
this.input = nodes;
}
//Some activation functions which can be called upon.
class ActivationFunction {
//Sigmoid activation function
public double sigmoid(double x) {
return (1.0 / (1 + Math.pow(Math.E, -x)));
}
public double deriveSigmoid(double d){
return d * (1.0 - d);
}
// Hyperbolic Tan Activation Function
public double hyperTanFunction(double x) {
return (Math.pow(Math.E, x) - Math.pow(Math.E, -x)) / (Math.pow(Math.E, x) + Math.pow(Math.E, -x));
}
public double deriveHyperTanFunction(double d){
return (1.0 - Math.pow(hyperTanFunction(d), 2.0));
}
}
//Output method for the HiddenNode class which will sum up all the input nodes for
//a specific hidden node
public double output(){
/*Here we will be implementing the following function
* Sigma(x[i] * weights[i]) = net
* Pass net into the hyberbolic tangent function to get an output between -1 to 1
* We will pass net into the activation function in the train method of Neural Network
*/
//Store inputs into s temp double array.
double[] tempArray = new double[input.length];
for (int j = 0; j < input.length; j++){
tempArray[j] = input[j].output();
System.out.println(tempArray[j]);
}
//Setup a double sum variable to represent net
double net = 0;
//Setup for loop to loop over input nodes array for a hidden node
for (int i = 0; i < tempArray.length; i++){
net = net + tempArray[i];
}
return net;
}
public static void main(String[] args) {
InputNode node1 = new InputNode(28);
InputNode node2 = new InputNode(0);
InputNode node3 = new InputNode(165);
InputNode node4 = new InputNode(30);
InputNode node5 = new InputNode(0);
InputNode node6 = new InputNode(0);
InputNode node7 = new InputNode(0);
InputNode[] nodes = {node1, node2, node3, node4, node5, node6, node7};
HiddenLayer h1 = new HiddenLayer(nodes);
h1.output();
}
}
InputNode.java
public class InputNode extends Node {
//Declare a double variable to represent the holding value for InputNode
private double value;
public InputNode(double value) {
}
//Create method to initialize input nodes
public void set(double tempValue){
this.value = tempValue;
}
public double get(){
return value;
}
//Override method from Node class
//This method will grab the sum of all input node values.
public double output(){
return number;
}
}
Well, as far as Java is concerned, you're only ever supplying the program with 0.
Take this line:
tempArray[j] = input[j].output();
output will be 0.0, as its initial value upon construction will be 0.0. The reason for this: output uses the field number to return its value, and since there's nowhere in your code that you explicitly assign number to a value, it will always be returning 0.0.
To fix it, depending on your logic or desired operation, you should initialize it either on InputNode's construction...
public InputNode(double value) {
number = value;
}
...or on Node's construction - forcing you to use the constructor described above:
public Node(double number) {
this.number = number;
}
public InputNode(double number) {
super(number);
}
I'm stuck on a mock exam question. I created a class called Power which allowed a number to be raised to any power.
The third part of the question asks me to create another class BoundedPower which would extend Power. I was given the MAX-X variable (x cannot exceed this value) and told that the BoundedPower class must: behave like the Power class, use a constructor and use thepowN method.
My code is below, i am not sure what to do to make the BoundedPower class work.
public class Power {
private double x = 0;
Power(double x) {
this.x = x;
}
public double getX() {
return x;
}
public double powN(int n) {
double result = 1.0;
for (int i = 0; i < n; i++) {
result = result * x;
}
return result;
}
public static void main(String[] args) {
Power p = new Power(5.0);
double d = p.powN(3);
System.out.println(d);
}
}
public class BoundedPower extends Power {
public static final double MAX_X = 1000000;
// invariant: x <= MAX_X
Power x;
BoundedPower(double x) {
super(x);
// this.x=x; x is private in Power class
}
public double powN(int n) {
if (x.getX() > MAX_X) {
return 0;
} else {
double result = 1.0;
for (int i = 0; i < n; i++) {
result = result * getX();
}
return result;
}
}
public static void main(String[] args) {
BoundedPower bp = new BoundedPower(5);
double test = bp.powN(4);
System.out.println(test);
}
}
There is no need for that instance Power variable x in your class. Any BoundedPower instance IS a Power instance, and as such, to reference a method from Power, do super.blah(), so for x.getX(), do super.getX()
Also, in your comments, you said this.x=x fails because its private. When you do the super call, it calls the constructor of the superclass (Power), which sets x there, so there is no need for this.x=x
public class BoundedPower extends Power {
public static final double MAX_X = 1000000;
BoundedPower(double x) {
super(x);
}
public double powN(int n) {
if (x.getX() > MAX_X) {
return 0;
} else {
return super.powN(n);
}
}
public static void main(String[] args) {
BoundedPower bp = new BoundedPower(5);
double test = bp.powN(4);
System.out.println(test);
}
}
You don't have to copy your computation formular to the subclass (just call super.powN(..)). You also don't need another instance of Power within BoundedPower.
This is probably what they had in mind:
public class Power {
public double powN(double x, int n) {
double result = 1.0;
for (int i = 0; i < n; i++) {
result = result * x;
}
return result;
}
}
public class BoundedPower extends Power {
private final double maxX;
public BoundedPower(double maxX) {
this.maxX = maxX;
}
public double powN(double x, int n) {
if (x > maxX) {
throw new IllegalArgumentException("x value [" + x + "] " +
"greater than expected max [" + maxX + "]");
}
return super.powN(x, n);
}
}
I would do it in a different way. From what you're saying the BoundedPower class makes sense only for a bounded x (up to MAX_X).
Consequently, I would not allow the creation of an object with an x greater than MAX_X (i.e. a BoundedPower object cannot exist for unbounded x's)
So the implementation would be exactly as the the Power implementation excepting the way you build BoundedPower instances : you first check whether it makes sense to build it
public class BoundedPower extends Power {
private static final double MAX_X = 1000000; //makes no sense to be public
public static BoundedPower newBoundedPower(int n)
throws IllegalNumberException{
if(x > MAX_X) throw new IllegalNumberException();
return new BoundedPower(x);
}
private BoundedPower(double x) {
super(x);
}
}
I am practicing recursion and I can't see why this method does not seem to work.
Any ideas?
public void fact()
{
fact(5);
}
public int fact(int n)
{
if(n == 1){
return 1;
}
return n * (fact(n-1));
}
}
Thanks
Your code seems to work but you are not doing anything with the returned value, put method call fact or fact(5) inside of a System.out.println and see what you get.
The recursion part is fine; you're just not using its return value, which gets discarded. Here's a complete Java application of your factorial code, slightly jazzed-up for educational purposes:
public class Factorial {
public static String fact(int n) {
if(n == 1){
return "1";
}
return n + " * " + (fact(n-1)); // what happens if you switch the order?
}
public static void main(String[] args) {
System.out.println(fact(5));
// prints "5 * 4 * 3 * 2 * 1"
}
}
A simplified version of your code:
public int fact(int n)
{
if(n == 1){
return 1;
}
return n * (fact(n-1));
}
could be just:
public int fact(int n)
{
return n == 1 ? 1 : n * fact(n - 1);
}
but your code is not wrong, this is just another style (if you are not used to ternary operator keep the way it is). I prefer use the ternary operator in these cases (observe that the code is side effect free).
Works fine. You're not assigning it to anything. Here's a test that'll prove it works.
#Test
public void testYourFactorialMethod() {
assertEquals(120, fact(5));
}
public class Recursive {
public static void main(String[] argss) {
System.out.print(fac(3));
}
public static int fac(int n) {
int value = 0;
if (n == 0) {
value = 1;
} else {
value = n * fac(n - 1);
}
return value;
}
}
// out put 6
Try something like this:
(Or maybe try this directly)
public class factorial {
private static int factorial( int n ){
if (n > 1) {
return n * (factorial(n-1));
} else {
return 1;
}
}
public static void main(String[] args) {
System.out.println(factorial(100));
}
}
static int factorial(int x) {
int result;
if (x == 1) {
return 1;
}
// Call the same method with argument x-1
result = factorial(x – 1) * x;
return result;
}
For complete example check this
http://answersz.com/factorial-program-in-java-using-recursion/
It is totaly wrong to write Fibonacci with recursive methods!!
It is an old famous example for how a good/bad Algorythm affect any project
if you write Fibonatcci recursive, for calculating 120 you need 36 year toget the result!!!!!!
public static int Fibonacci(int x)
{ // bad fibonacci recursive code
if (x <= 1)
return 1;
return Fibonacci(x - 1) + Fibonacci(x - 2);
}
in dot net 4.0 there is a new type name BigInteger and you can use it to make a better function
using System;
using System.Collections.Generic;
using System.Numerics; //needs a ref. to this assembly
namespace Fibonaci
{
public class CFibonacci
{
public static int Fibonacci(int x)
{
if (x <= 1)
return 1;
return Fibonacci(x - 1) + Fibonacci(x - 2);
}
public static IEnumerable<BigInteger> BigFib(Int64 toNumber)
{
BigInteger previous = 0;
BigInteger current = 1;
for (Int64 y = 1; y <= toNumber; y++)
{
var auxiliar = current;
current += previous;
previous = auxiliar;
yield return current;
}
}
}
}
and you can use it like
using System;
using System.Linq;
namespace Fibonaci
{
class Program
{
static void Main()
{
foreach (var i in CFibonacci.BigFib(10))
{
Console.WriteLine("{0}", i);
}
var num = 12000;
var fib = CFibonacci.BigFib(num).Last();
Console.WriteLine("fib({0})={1}", num, fib);
Console.WriteLine("Press a key...");
Console.ReadKey();
}
}
}
and in this case you can calculate 12000 less than a second. so
Using Recursive methos is not always a good idea
Above code imported from Vahid Nasiri blog whiche wrote in Persian