I want to calculate the sum of this function ((-1)^n)*(x^2n)/(2.n!) but my program isn't working.I need your help.Here's what i tried:
public double getCos()
{
double Cos = 0;
for(int i=0;i<=n;i++)
{
Cos+=(power(x,i)/facto(n));
}
return Cos;
}
private double facto(int n)
{
for (int i = 1; i <= n; i++) {
result = result * i;
}
return result*2;
}
private double power(int x,int n)
{
double power=Math.pow(-1,n)*Math.pow(x,2*n);
return power;
}
}
This is How You Make It I Just Fix Some Errors On Your Program :
public class Cos {
public static double getCos(double x) {
double Cos = 0;
for (int i = 0; i <= 5; i++) {
Cos += (power(-1, i) * power(x, 2*i)) / factorial(2*i) ;
}
return Cos;
}
public class Cos {
public static double getCos(double x) {
double Cos = 0;
for (int i = 0; i <= 5; i++) {
Cos += (power(-1, i) * power(x, 2*i)) / factorial(2*i) ;
}
return Cos;
}
private static double factorial(int n) {
int result = 1;
if( n == 0 || n == 1 )
return 1;
else {
for (int i = 1; i <= n; i++) {
result = result * i;
}
return result;
}
}
private static double power(double x, int n) {
return Math.pow(x, n);
}
public static void main(String[] args) {
System.out.println("Test For The 3 Methods!");
System.out.println("5^2 : " + power(5, 2));
System.out.println("4! : " + factorial(4));
System.out.println("Cos(0.2) : " + getCos(0.2));
}
}
private static double power(double x, int n) {
return Math.pow(x, n);
}
public static void main(String[] args) {
System.out.println("Test For The 3 Methods!");
System.out.println("5^2 : " + power(5, 2));
System.out.println("4! : " + factorial(4));
System.out.println("Cos(0.2) : " + getCos(0.2));
}
}
From what I can tell, your difficulties are arising in your facto method. First of all, result was never properly declared (at least in the code provided). Furthermore, when 0 is passed for the first term, i=1 and therefore i<=0 evaluates false and the loop never executes. So what value would result have?
private double facto(int n) {
if(n==0) return 1.0;
double result = 0.0;
for (int i = 1; i <= n; i++) {
result = result * i;
}
return result*2;
}
This is How I Will Make This Exercise :
public class TaylorSeries {
static double power(double x,int n)
{
double p = 1;
for (int i = 1; i <= n ; i++) {
p = p*x;
}
return p;
}
// this is the best way to make factorial function by recursion
static int factorial(int n)
{
if(n == 1 || n == 0)
{
return 1;
}
else
{
return n*factorial(n - 1);
}
}
// i = 0 to i = 5 the 5 is for the summation
static double cos(double x)
{
double cos = 0;
for (int i = 0; i <= 5 ; i++) {
cos += ( power(-1, i) * power(x, 2*i) ) / ( factorial(2*i) );
}
return cos;
}
public static void main(String[] args) {
System.out.println("2^3 : " + power(2, 3));
System.out.println("5! : " + factorial(5));
// 20 means summation from 0 to 20
System.out.println("Cos(0.15) : " + cos(0.15));
}
}
Related
Ex: n1=100, n2=250, out=233.
Here I have to find the largest odd fibonacci number in the given set of ranges. If an odd fibonacci number doesn't exist then it should return 0. I am getting output as 50 times 0's and then 10 times 233. Where is my mistake and how can I get the desired output?
public class Fibo {
public static void main(String[] args) {
try {
int n1 = 100;
int n2 = 250;
int res = 0;
if (n1 % 2 == 0) {
n1 += 1;
for (int i = n1; i < n2; i += 2) {
if (isPerfectSquare(5 * i * i + 4) || isPerfectSquare(5 * i * i - 4))
res = i;
System.out.println(res);
}
}
} catch(Exception ignored) {
System.out.println("0");
}
}
public static boolean isPerfectSquare(int num) {
double sqrt = Math.sqrt(num);
int x = (int)sqrt;
return Math.pow(sqrt, 2) == Math.pow(x, 2);
}
}
public class Fibonacci {
public static void main(String[] args) {
System.out.println("Enter the starting range");
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
System.out.println("Enter the ending range");
int r = sc.nextInt();
int res = 0;
for (int i = n; i <= r; i++) {
if (isPerfectSquare(5 * i * i + 4) || isPerfectSquare(5 * i * i - 4))
res = i;
}
System.out.println("The biggest odd number in the range is"+" "+res);
}
public static boolean isPerfectSquare(int num) {
double sqrt = Math.sqrt(num);
int x = (int)sqrt;
return Math.pow(sqrt, 2) == Math.pow(x, 2);
}
}
public static int getLargestOddFibonacciBetween(int lo, int hi) {
assert lo <= hi;
int f0 = 0;
int f1 = 1;
int res = -1;
while (f1 <= hi) {
int val = f0 + f1;
f0 = f1;
f1 = val;
if (val >= lo && val <= hi && isOdd(val))
res = val;
}
return res;
}
private static boolean isOdd(int val) {
return (val & 1) == 1;
}
I'm trying to do the Algorithm programming assignment of Princeton , and I met a problem about the memory test. The assignment requires us run the percolation program N times and find the medium of the result, and I write a percolationtest.java and for each time, I create an instance variable, it worked, but use too much memory, and the instructor suggests me to use local variable, but I don't know how. Can some one help me and give me some advice, I really appreciate it.
public class PercolationStats {
private int N, T, totalSum;
private double []fraction;
private int []count;
public PercolationStats(int N, int T) {
if (N <= 0 || T <= 0)
throw new IllegalArgumentException();
else {
this.N = N;
this.T = T;
count = new int [T];
totalSum = N*N;
fraction = new double[T];
int randomX, randomY;
for (int i = 0; i < T; i++) {
Percolation perc = new Percolation(N);
while (true) {
if (perc.percolates()) {
fraction[i] = (double) count[i]/totalSum;
break;
}
randomX = StdRandom.uniform(1, N+1);
randomY = StdRandom.uniform(1, N+1);
if (perc.isOpen(randomX, randomY)) continue;
else {
perc.open(randomX, randomY);
count[i]++;
}
}
}
}
} // perform T independent experiments on an N-by-N grid
public double mean() {
double totalFraction = 0;
for (int i = 0; i < T; i++) {
totalFraction += fraction[i];
}
return totalFraction/T;
} // sample mean of percolation threshold
public double stddev() {
double u = this.mean();
double sum = 0;
for (int i = 0; i < T; i++) {
sum += (fraction[i] - u) * (fraction[i] - u);
}
return Math.sqrt(sum/(T-1));
} // sample standard deviation of percolation threshold
public double confidenceLo() {
double u = this.mean();
double theta = this.stddev();
double sqrtT = Math.sqrt(T);
return u-1.96*theta/sqrtT;
} // low endpoint of 95% confidence interval
public double confidenceHi() {
double u = this.mean();
double theta = this.stddev();
double sqrtT = Math.sqrt(T);
return u+1.96*theta/sqrtT;
} // high endpoint of 95% confidence interval
public static void main(String[] args) {
int N = 200;
int T = 100;
if (args.length == 1) N = Integer.parseInt(args[0]);
else if (args.length == 2) {
N = Integer.parseInt(args[0]);
T = Integer.parseInt(args[1]); }
PercolationStats a = new PercolationStats(N, T);
System.out.print("mean = ");
System.out.println(a.mean());
System.out.print("stddev = ");
System.out.println(a.stddev());
System.out.print("95% confidence interval = ");
System.out.print(a.confidenceLo());
System.out.print(", ");
System.out.println(a.confidenceHi());
}
}
public class Percolation {
private boolean[][] site;
private WeightedQuickUnionUF uf;
private int N;
public Percolation(int N) {
if (N < 1)
throw new IllegalArgumentException();
else {
site = new boolean[N + 2][N + 2];
for (int j = 1; j <= N; j++) {
site[0][j] = true;
site[N + 1][j] = true;
}
uf = new WeightedQuickUnionUF((N + 2) * (N + 2));
for (int i = 1; i <= N; i++) {
uf.union(0, i);
}
this.N = N;
}
}
public void open(int i, int j) {
if (i > N || i < 1 || j > N || j < 1)
throw new IndexOutOfBoundsException();
else {
if (!site[i][j]) {
site[i][j] = true;
if (site[i - 1][j]) {
uf.union((N + 2) * (i - 1) + j, (N + 2) * i + j);
}
if (site[i + 1][j]) {
uf.union((N + 2) * i + j, (N + 2) * (i + 1) + j);
}
if (site[i][j + 1]) {
uf.union((N + 2) * i + (j + 1), (N + 2) * i + j);
}
if (site[i][j - 1]) {
uf.union((N + 2) * i + (j - 1), (N + 2) * i + j);
}
}
}
}
public boolean isOpen(int i, int j) {
if (i > N || i < 1 || j > N || j < 1)
throw new IndexOutOfBoundsException();
else
return site[i][j];
}
public boolean isFull(int i, int j) {
if (i > N || i < 1 || j > N || j < 1)
throw new IndexOutOfBoundsException();
else
return site[i][j] && (i == 1 || uf.connected((N + 2) * i + j, 0));
}
public boolean percolates() {
for (int i = 1; i <= N; i++) {
if (this.isFull(N, i)) {
return true;
}
}
return false;
}
public static void main(String[] args) {
}
}
Added meanValue instance variable to keep mean value and replaced it in multiple places where you used to call mean() method which was over head to calculate again and again. Also modified "int[] count" as local variable which you were not using outside the constructor. post your "Percolation" and "StdRandom" classes for more optimization of code. you can run this code and test, it should reduce the runtime than yours.
public class PercolationStats {
private int N, T, totalSum;
private double []fraction;
private double meanValue;
public PercolationStats(int N, int T) {
if (N <= 0 || T <= 0)
throw new IllegalArgumentException();
else {
this.N = N;
this.T = T;
int [] count = new int [T];
totalSum = N*N;
fraction = new double[T];
int randomX, randomY;
for (int i = 0; i < T; i++) {
Percolation perc = new Percolation(N);
while (true) {
if (perc.percolates()) {
fraction[i] = (double) count[i]/totalSum;
break;
}
randomX = StdRandom.uniform(1, N+1);
randomY = StdRandom.uniform(1, N+1);
if (perc.isOpen(randomX, randomY)) continue;
else {
perc.open(randomX, randomY);
count[i]++;
}
}
}
}
}
// perform T independent experiments on an N-by-N grid
public double mean() {
double totalFraction = 0;
for (int i = 0; i < T; i++) {
totalFraction += fraction[i];
}
meanValue = totalFraction/T;
return meanValue;
} // sample mean of percolation threshold
public double stddev() {
double u = meanValue;
double sum = 0;
for (int i = 0; i < T; i++) {
sum += (fraction[i] - u) * (fraction[i] - u);
}
return Math.sqrt(sum/(T-1));
} // sample standard deviation of percolation threshold
public double confidenceLo() {
double u = meanValue;
double theta = this.stddev();
double sqrtT = Math.sqrt(T);
return u-1.96*theta/sqrtT;
} // low endpoint of 95% confidence interval
public double confidenceHi() {
double u = meanValue;
double theta = this.stddev();
double sqrtT = Math.sqrt(T);
return u+1.96*theta/sqrtT;
} // high endpoint of 95% confidence interval
public static void main(String[] args) {
int N = 200;
int T = 100;
if (args.length == 1) N = Integer.parseInt(args[0]);
else if (args.length == 2) {
N = Integer.parseInt(args[0]);
T = Integer.parseInt(args[1]); }
PercolationStats a = new PercolationStats(N, T);
System.out.print("mean = ");
System.out.println(a.mean());
System.out.print("stddev = ");
System.out.println(a.stddev());
System.out.print("95% confidence interval = ");
System.out.print(a.confidenceLo());
System.out.print(", ");
System.out.println(a.confidenceHi());
}
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I have to compare two strings which 4000-5000 characters.
I need result in percentage(i.e. 70% - 80% matched), in java.
Kindly suggest me any solution for it.
Regards
Here is the code to compare two strings and getting result in integer form from 0 to 100.
/**
*
* #author WARLOCK
*/
public class LockMatch {
public static void main(String arg[]) {
//---Provide source and target strings to lock_match function to compare--//
System.out.println("Your Strings are Matched="+lock_match("The warlock","The warlock powered by WTPL")+"%");
}
public static int lock_match(String s, String t) {
int totalw = word_count(s);
int total = 100;
int perw = total / totalw;
int gotperw = 0;
if (!s.equals(t)) {
for (int i = 1; i <= totalw; i++) {
if (simple_match(split_string(s, i), t) == 1) {
gotperw = ((perw * (total - 10)) / total) + gotperw;
} else if (front_full_match(split_string(s, i), t) == 1) {
gotperw = ((perw * (total - 20)) / total) + gotperw;
} else if (anywhere_match(split_string(s, i), t) == 1) {
gotperw = ((perw * (total - 30)) / total) + gotperw;
} else {
gotperw = ((perw * smart_match(split_string(s, i), t)) / total) + gotperw;
}
}
} else {
gotperw = 100;
}
return gotperw;
}
public static int anywhere_match(String s, String t) {
int x = 0;
if (t.contains(s)) {
x = 1;
}
return x;
}
public static int front_full_match(String s, String t) {
int x = 0;
String tempt;
int len = s.length();
//----------Work Body----------//
for (int i = 1; i <= word_count(t); i++) {
tempt = split_string(t, i);
if (tempt.length() >= s.length()) {
tempt = tempt.substring(0, len);
if (s.contains(tempt)) {
x = 1;
break;
}
}
}
//---------END---------------//
if (len == 0) {
x = 0;
}
return x;
}
public static int simple_match(String s, String t) {
int x = 0;
String tempt;
int len = s.length();
//----------Work Body----------//
for (int i = 1; i <= word_count(t); i++) {
tempt = split_string(t, i);
if (tempt.length() == s.length()) {
if (s.contains(tempt)) {
x = 1;
break;
}
}
}
//---------END---------------//
if (len == 0) {
x = 0;
}
return x;
}
public static int smart_match(String ts, String tt) {
char[] s = new char[ts.length()];
s = ts.toCharArray();
char[] t = new char[tt.length()];
t = tt.toCharArray();
int slen = s.length;
//number of 3 combinations per word//
int combs = (slen - 3) + 1;
//percentage per combination of 3 characters//
int ppc = 0;
if (slen >= 3) {
ppc = 100 / combs;
}
//initialising an integer to store the total % this class genrate//
int x = 0;
//declaring a temporary new source char array
char[] ns = new char[3];
//check if source char array has more then 3 characters//
if (slen < 3) {
} else {
for (int i = 0; i < combs; i++) {
for (int j = 0; j < 3; j++) {
ns[j] = s[j + i];
}
if (cross_full_match(ns, t) == 1) {
x = x + 1;
}
}
}
x = ppc * x;
return x;
}
/**
*
* #param s
* #param t
* #return
*/
public static int cross_full_match(char[] s, char[] t) {
int z = t.length - s.length;
int x = 0;
if (s.length > t.length) {
return x;
} else {
for (int i = 0; i <= z; i++) {
for (int j = 0; j <= (s.length - 1); j++) {
if (s[j] == t[j + i]) {
// x=1 if any charecer matches
x = 1;
} else {
// if x=0 mean an character do not matches and loop break out
x = 0;
break;
}
}
if (x == 1) {
break;
}
}
}
return x;
}
public static String split_string(String s, int n) {
int index;
String temp;
temp = s;
String temp2 = null;
int temp3 = 0;
for (int i = 0; i < n; i++) {
int strlen = temp.length();
index = temp.indexOf(" ");
if (index < 0) {
index = strlen;
}
temp2 = temp.substring(temp3, index);
temp = temp.substring(index, strlen);
temp = temp.trim();
}
return temp2;
}
public static int word_count(String s) {
int x = 1;
int c;
s = s.trim();
if (s.isEmpty()) {
x = 0;
} else {
if (s.contains(" ")) {
for (;;) {
x++;
c = s.indexOf(" ");
s = s.substring(c);
s = s.trim();
if (s.contains(" ")) {
} else {
break;
}
}
}
}
return x;
}
}
Just supply the two strings as argument to lock_match(string1, string2) and it will return the integer value of matching. If the size of string is bigger then increase the total name variable size
in the code.
Like int total=1000
Then the result will be given out of 0 to 1000.
This code is case sensitive.
Uppercase or lowercase both strings to get rid from this problem.
Source code available at: lock match
You can use Apache Commons Lang 3.
Maven dependency:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons.lang.version}</version>
</dependency>
#Test
public void test_stringDistance() throws Exception {
String teamName = "Partizn Belgrade";
String propositionName = "Partizan Belgrade";
// This one seems better
double distance = StringUtils.getJaroWinklerDistance(teamName, propositionName);
System.out.println(distance);
}
This is print out percentage, the larger the better (100% is exact )
org.apache.commons.lang3.StringUtils.getJaroWinklerDistance(first, second) is deprecated as of commons-lang3:3.6
Use new org.apache.commons.text.similarity.JaroWinklerDistance().apply(left, right) instead where left and right stand for first and second respectively. See maven dependency below
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-text</artifactId>
<version>1.9</version>
</dependency>
public class PalindromicPrimes {
public static void main (String[] args) {
userInt();
System.out.println("The palindromic primes less than " + userInt() +
" are:");
for (int i = 0; i <= userInt(); i++) {
if (isPrime() && isPalindrome()) {
System.out.println(i);
}
}
}
private static boolean isPrime() {
if (userInt() == 2 || userInt() == 3) {
return true;
}
if (userInt() % 2 == 0) {
return false;
}
int sqrt = (int) Math.sqrt(userInt()) + 1;
for (int i = 3; i < sqrt; i += 2) {
if (userInt() % i == 0) {
return false;
}
}
return true;
}
private static boolean isPalindrome() {
if (userInt() < 0)
return false;
int div = 1;
while (userInt() / div >= 10) {
div *= 10;
}
while (userInt() != 0) {
int x = userInt();
int l = x / div;
int r = x % 10;
if (l != r)
return false;
x = (x % div) / 10;
div /= 100;
}
return true;
}
private static int userInt() {
Scanner s = new Scanner(System.in);
System.out.print("Enter a positive integer: ");
int userInt = s.nextInt();
return userInt;
}
}
is there a different way of getting the user input? or can I keep it this way?
when it runs it just keeps prompting the user input.
rearrange it like this:
public static void main (String[] args) {
//get it and save it here!
int userValue = userInt();
System.out.println("The palindromic primes less than " + userValue +
" are:");
for (int i = 0; i <= userValue; i++) {
if (isPrime(userValue) && isPalindrome(userValue)) {
System.out.println(i);
}
}
}
then also update all the methods that care about this "userInt" value.
Every time you call userInt() you're telling the code to get a new value from the command line.
Try this:
public static void main (String[] args) {
int value = userInt();
System.out.println("The palindromic primes less than " + value +
" are:");
for (int i = 0; i <= value; i++) {
if (isPrime() && isPalindrome()) {
System.out.println(i);
}
}
}
The term userInt() is a function invocation that prompts the user for input. Odds are you only want to do this once. You're doing it multiple times.
You should store the result of userInt() in a variable.
int typed = userInt();
And then use this variable to reference what the user typed instead of calling userInt() again.
System.out.println("The palindromic primes less than " + typed +
" are:");
for(int i = 0; i < typed; i++) ...
You keep calling userInt(). That is the problem.
I don't understand your logic. So I have not modified that code. But the code runs.
import java.util.Scanner;
public class PalindromicPrimes {
public static void main (String[] args) {
int x = userInt();
System.out.println("The palindromic primes less than " + x +
" are:");
for (int i = 0; i <= x; i++) {
if (isPrime(i) && isPalindrome(i)) {
System.out.println(i);
}
}
}
private static boolean isPrime(int a) {
if (a == 2 || a == 3) {
return true;
}
if (a % 2 == 0) {
return false;
}
int sqrt = (int) Math.sqrt(a) + 1;
for (int i = 3; i < sqrt; i += 2) {
if (a % i == 0) {
return false;
}
}
return true;
}
private static boolean isPalindrome(int a) {
if (a < 0)
return false;
int div = 1;
while (a / div >= 10) {
div *= 10;
}
while (a != 0) {
int x = a;
int l = x / div;
int r = x % 10;
if (l != r)
return false;
x = (x % div) / 10;
div /= 100;
}
return true;
}
private static int userInt() {
Scanner s = new Scanner(System.in);
System.out.print("Enter a positive integer: ");
int userInteger = s.nextInt();
return userInteger;
}
}
Remember, don't use the same names for variable and function. In the function userInt(), you have used a variable int userInt, to get the result from the scanner. This might be aa recursive call sometimes. Be careful with that.
I designing a polynomial class for one of my com sci courses , I have a problem of getting the integration method right
can some one help me with that
/** The polynomial class includes the methods: evaluate , add, multiply,
* Differentiate , integrate and square root.
*/
public class polynomial {
private int degree;
private double[] coefficients;
// a constructor that creates a polynomial of degree degMax with all the coefficients are zeroes
public polynomial(int degMax) {
degree= degMax;
coefficients = new double[degree + 1];
}
// a setter method that let the users set the coefficients for the polynomial they constructed
public void setCoefficient(int d , double v ){
if (d > degree)
{
System.out.println("Erorr Message: the degree you specified is larger than the polynomial's degree that you have created ");
}
else {
coefficients[d]=v;
}
}
// a getter method to return the coefficient for the specified degree
public double getCoefficient(int i){
return coefficients[i];
}
// private method that counts the degree of the polynomial by searching for the last element in the coefficient array that
// does not contain zero
private int getDegree() {
int deg = 0;
for (int i = 0; i < coefficients.length; i++)
if (coefficients[i] != 0) deg = i;
return deg;
}
// a method that print out the polynomial as a string
public String print(){
if (degree == 0) return "" + coefficients[0];
if (degree == 1) return coefficients[1] + "x + " + coefficients[0];
String s = coefficients[degree] + "x^" + degree;
for (int i = degree-1; i >= 0; i--) {
if (coefficients[i] == 0) continue;
else if (coefficients[i] > 0) s = s + " + " + ( coefficients[i]);
else if (coefficients[i] < 0) s = s + " - " + (-coefficients[i]);
if (i == 1) s = s + "x";
else if (i > 1) s = s + "x^" + i;
}
return s;
}
// a method that evaluate the polynomial at specified value x
public double evaluate(double x) {
double result = 0;
for (int i = degree; i >= 0; i--)
result = coefficients[i] + (x * result);
return result;
}
// a method that perform symbolic addition of two polynomial
public polynomial addition(polynomial p2) {
polynomial p1 = this;
polynomial p3 = new polynomial(Math.max(p1.degree, p2.degree));
for (int i = 0; i <= p1.degree; i++) p3.coefficients[i] += p1.coefficients[i];
for (int i = 0; i <= p2.degree; i++) p3.coefficients[i] += p2.coefficients[i];
p3.degree = p3.getDegree();
return p3;
}
// a method that performs a symbolic multiplication
public polynomial multiply(polynomial p2) {
polynomial p1 = this;
polynomial p3 = new polynomial(p1.degree + p2.degree);
for (int i = 0; i <= p1.degree; i++)
for (int j = 0; j <= p2.degree; j++)
p3.coefficients[i+j] += (p1.coefficients[i] * p2.coefficients[j]);
p3.degree = p3.getDegree();
return p3;
}
// a method that apply differentiation to polynomial
public polynomial differentiate() {
if (degree == 0) return new polynomial(0);
polynomial derivative = new polynomial(degree - 1);
derivative.degree = degree - 1;
for (int i = 0; i < degree; i++){
derivative.coefficients[i] = (i + 1) * coefficients[i + 1];
}
return derivative;
}
// a method that find a polynomial integral over the interval a to b
public double integration(double a , double b) {
polynomial integral= new polynomial (degree+1);
integral.degree= degree+1;
for (int i=0 ; i<= degree+1 ; i++){
if (i==0) {
integral.coefficients[i]= 0;
}
else {
integral.coefficients[i]= (coefficients[i-1]/i);
}
}
return (evaluate(b)- evaluate(a));
}
public static void main(String[] args) {
polynomial p1 = new polynomial(3);
p1.setCoefficient(0, 3.0);
p1.setCoefficient(3, 5.0);
String r = p1.print(); //3.0 + 5.0 x^3
polynomial p2 = new polynomial(2);
p2.setCoefficient(1, 4.0);
p2.setCoefficient(2, 2.0);
polynomial n = p1.addition(p2);
String po = n.print();
polynomial t = p1.multiply(p2);
String tr = t.print();
polynomial di = p2.differentiate();
String dir = di.print();
double ev = p2.evaluate(5.0);
double inte = p1.integration(3.0, 7.0);
System.out.println("p1(x) = " + r );
System.out.println("p1(x) + p2(x) = " + po);
System.out.println("p1(x) * p2(x) = " + tr);
System.out.println("p2'(x) = " + dir);
System.out.println("p1(x) integration over [3.0, 7.0] = " + inte);
System.out.println("p2(5.0) = " + ev);
}
}
If I were you, I would split the methods :
public Polynomial integrate()
{
Polynomial integral = new Polynomial(this.degree + 1);
for (int i = 1; i <= this.degree+1; i++)
{
integral.coefficients[i] = (this.coefficients[i - 1] / i);
}
return integral;
}
// a method that find a Polynomial integral over the interval a to b
public double integration(double a, double b)
{
Polynomial integral = integrate();
return (integral.evaluate(b) - integral.evaluate(a));
}
Ok now why it didn't work as you expected :
public double integration(double a , double b) {
polynomial integral= new polynomial (degree+1);
integral.degree= degree+1;
for (int i=0 ; i<= degree+1 ; i++){
if (i==0) {
integral.coefficients[i]= 0;
}
else {
integral.coefficients[i]= (coefficients[i-1]/i);
}
}
return (evaluate(b)- evaluate(a));
}
you messed up your "integral" object with the current instance "this", clean your code first :
public double integration(double a , double b) {
polynomial integral= new polynomial (this.degree+1);
integral.degree= this.degree+1;
for (int i=0 ; i<= this.degree+1 ; i++){
if (i==0) {
integral.coefficients[i]= 0;
}
else {
integral.coefficients[i]= (this.coefficients[i-1]/i);
}
}
return (this.evaluate(b)- this.evaluate(a));
}
Here you can see that you evaluate on your instance object instead of "integral" object. That's why it messed up the result.
You almost got it correct. The only problem is that you should call:
return (integral.evaluate(b) - integral.evaluate(a));
instead of:
return (evaluate(b)- evaluate(a));
Otherwise the code seems ok.
Adding to Boris' answer, you could simplify the integrate method like this:
public double integration(double a, double b) {
polynomial integral = new polynomial(degree + 1);
for (int i = 1; i <= degree + 1; i++) {
integral.coefficients[i] = coefficients[i - 1] / i;
}
return integral.evaluate(b) - integral.evaluate(a);
}