Can Self-Written Math Functions Replace Standard Java Libraries?

  • Context: Java 
  • Thread starter Thread starter PrudensOptimus
  • Start date Start date
  • Tags Tags
    Functions hand
Click For Summary

Discussion Overview

The discussion revolves around the feasibility and effectiveness of self-written mathematical functions as replacements for standard Java libraries. Participants examine the code provided by Tom Zhang, focusing on its structure, efficiency, and adherence to object-oriented programming principles.

Discussion Character

  • Technical explanation
  • Debate/contested
  • Conceptual clarification

Main Points Raised

  • Tom Zhang presents a set of self-written mathematical functions, emphasizing the absence of predefined math functions to showcase coding abilities.
  • Some participants criticize the code for being messy and suggest that it could be optimized, particularly the square root function, by using methods like Newton's method or lookup tables.
  • There is a question raised about the object-oriented nature of the code, with some participants seeking clarification on how it meets those principles.
  • One participant points out a potential error in the ceiling function implementation, claiming it produces incorrect results.
  • Another participant suggests that the use of a more precise value for Pi would improve the code, noting that Java provides a built-in constant for this purpose.
  • Concerns are expressed regarding the computational complexity of the algorithms used, with a recommendation to learn about Taylor and Maclaurin series for better precision and efficiency.
  • Participants also discuss formatting issues in the forum that may affect the readability of the code.

Areas of Agreement / Disagreement

Participants express a mix of agreement and disagreement regarding the quality and efficiency of the code. While some acknowledge the effort, others highlight significant areas for improvement and optimization. The discussion remains unresolved on several technical points, including the correctness of specific functions and the overall object-oriented design.

Contextual Notes

Limitations include potential inaccuracies in the mathematical implementations, unresolved questions about object-oriented principles, and varying opinions on the efficiency of the algorithms used.

PrudensOptimus
Messages
641
Reaction score
0
Excerpt of my selfwritten math functions, enjoy.


Code:
/*+++++++++++++++++++++++++
/*Project III
/*Object Oriented Programming
/*Dr. Fani Milanova
/*Tom Zhang
/*
/*Note: No java package was 
/*      imported. Everything
/*      was done by selfmade
/*      functions.
/*      This demonstrates
/*      great math and coding
/*      abilities without use
/*      of predefined math
/*      functions.
/*++++++++++++++++++++++++*/

public class Project3 {
	public static void main (String[] args) {
		displayCalcOutput();
	}
	
	static void displayCalcOutput(){
		int var1 = 12;
		int var2 = 20;
		int var3 = 37;
		double var4 = 45;
		double var5 = 55;
		double var6 = -16;
				
		float fltVar1 = (float)25.3;
		float fltVar2 = (float)13.5;
		float fltVar3 = (float)25.5;
		
	/* MAIN */
	System.out.println("+++++++++++++++++++++++++++++++++++++++" + '\n' +
					   "+ Project III by Tom Zhang             " + '\n' + 
					   "+++++++++++++++++++++++++++++++++++++++" + '\n' +
					   " ");
		//a: Difference of var 3 and var2
		int var2_1 = var3 - var2;
		System.out.println(" (var3 - var2) = (" + var3 + " - " + var2 + ") = " + var2_1);
		
		//b: Quotient of var4 and var5
		double var4_1 = var4/var5;
		System.out.println(" (var4 / var5) = (" + var4 + " / " + var5 + ") = " + var4_1);
		
		//c: Abs of var6
		if(var6 <0)
		var6 *= -1;
		System.out.println(" |var6| = |" + (-var6) + "| = " + var6);
		//d: 4th power of var4
		System.out.println(" (var4*var4*var4*var4) = (var4^4) = " + Power(var4,4));
		
		//e: Sin(var4)
		System.out.println(" Sin(" + var4 + ") = " + Sin(var4,'d'));
		
		//f: Sqrt(var5)
		System.out.println(" Sqrt(" + var5 + ") = " + Sqrt(var5));
		
		//g: Floor(fltVr3)
		System.out.println(" Floor(" + fltVar3 + ") = " + Floor(fltVar3));

		//h: Ceil(fltVr3)
		System.out.println(" Ceil(" + fltVar3 + ") = " + Ceil(fltVar3));
				
		//i: Log(var3)
		System.out.println(" Log(" + var3 + ") = " + Log(var3));
		
		//j: Result
		double result = ((var1 + var2 - var5)/fltVar1) + ((fltVar3*Power(var1,var2))-var1);
		System.out.println(" -------------------------------------------- " + '\n' +
						   " Result:  " + result );
		
		System.out.println('\n');

	}		
	
	static double Power(double a, int b) {
		// Power(a,b) = a^b, where b is integer.
		double j = 1.0;
		for (int i = 1; i <= b; i++){
			j *= a;
		}
		return j;
	}
		
	static double Sin(double a, int b) {
		//Sine is an infinite series composed of both negative and positive "odd" terms.
		//My approach is to split into "odd" positive and negative parts and sum up.
		//But first let us do some conversions necessary.
		switch (b) {
			case 'd':
			//Convert to radians
			a *= (3.14/180);
			break;
			case 'r': 
			break;
		}
		
		//Declare v for pos ones, sign for the sign.
		double v = 0.0;
		int sign = -1;
		
		
		for(int i = 1; i <= 10; i+=2){
			sign = -sign;
			v += sign*(Power(a, i)/Factorial(i));
		}
		
		
		//Sum
		return v;
	}
	static double Factorial(int a) {
		//Factorial a! is defined to be a(a-1)(a-2)...(a-i) or j(j+1)(j+2)...(a)
		//Example: 7! = 7(7-1)(7-2)...(7-6) = 1(2)(3)(4)...(7).
		
		double j = 1.0;
		for (int i = 1; i < a; i++) {
			j *= i;
		}
		return j*a;
	}
	static double Sqrt(double a) {
		//There is really no easy way to find sqrts out of scratch.
		//You can expand it, but as numbers vary, inaccurcy varies greatly.
		//Thus, my intention is to loop until b*b is about a.
		double b = 0;
		
		while((b*b) <= a) {
			b += 0.0001;
		}
		
		return b;
	}
	static double Log(double a) {
		//Log(a) is also known as 10^b = a, where b = Log(a).
		//Since the expansion for Log(a) is very complex and is not needed at this level,
		//I will approach Log(a) the same way I approached Sqrt(a).
		//Except this time b could be a decimal... Power() wouldn't work, so I have to 
		//write a new PowerDec Function.
		
		double b = 0;
		
		while(PowerDec(10,b) <= a) {
			b += 0.11;
		}
		
		return b;
	}
	static double PowerDec(double x, double a){
		//Evaluates decimal powers from i+0.01 -> i+0.99
		double b = 0;//value of the root.
		int i = 0; 
		//Check special cases
		if (a == 1)
		return x;
		
		//Check power if > 1.
		while (a > 1) {
			a -= 1;
			i += 1;
		}

	
		//MAIN		
		
		if( (a>=0.01) && (a<0.125)  ){ //0.11 1/9
			while ((b*b*b*b*b*b*b*b*b) <= x) {
				b += 0.0001;
			}
		}				
		if( (a>=0.125) && (a<0.14)  ){ //0.125 1/8
			while ((b*b*b*b*b*b*b*b) <= x) {
				b += 0.0001;
			}
		}				
		if( (a>=0.16) && (a<=0.17)  ){ //0.16 1/6
			while ((b*b*b*b*b*b) <= x) {
				b += 0.0001;
			}
		}		
		if( (a>=0.14) && (a<0.17)  ){ //0.14 1/7
			while ((b*b*b*b*b*b*b) <= x) {
				b += 0.0001;
			}
		}
		if( (a>0.17) && (a<0.25) ){ //0.2
			while ((b*b*b*b*b) <= x) {
				b += 0.0001;
			}
		}
		if( (a>=0.25) && (a<0.3) ) {//0.25
			while ((b*b*b*b) <= x) {
				b += 0.0001;
			}
		}
		if( (a>=0.3) && (a<0.45) ) {//0.3
			while ((b*b*b) <= x) {
				b += 0.0001;
			}
		}
		if( (a>=0.45) && (a<0.55) ) {//0.5, just call sqrt
			b=Sqrt(x);
		}
		if( (a>=0.55) && (a<0.65) ) {//0.6, 3/5
			while ((b*b*b*b*b) <= (x*x*x)) {
				b += 0.0001;
			}
		}
		if( (a>=0.65) && (a<0.75) ) {//0.7, 7/10
			while ((b*b*b*b*b*b*b*b*b*b) <= (x*x*x*x*x*x*x)) {
				b += 0.0001;
			}
		}
		if( (a>=0.75) && (a<0.85) ) {//0.8, 4/5
			while ((b*b*b*b*b) <= (x*x*x*x)) {
				b += 0.0001;
			}
		}
		if( (a>=0.85) && (a<=0.99) ) {//0.9, 9/10
			while ((b*b*b*b*b*b*b*b*b*b) <= (x*x*x*x*x*x*x*x*x)) {
				b += 0.0001;
			}
		}		
					
		//Check if i>=1, multiply b by x i times until i becomes less than 1. 
		//IE x^(1.2) = x^1 * x^0.2 
		while (i>=1) {
			b *= x;
		    i -= 1;
		}
		return b;
	}
	static int Floor(float z) {
		return (int)z;
	}
	static int Ceil(float z) {
		return (int)(z+1);
	}	
}
 
Last edited:
Technology news on Phys.org
That is some really messy code. You should look into taking an algorithms class. Your code could run a lot faster if you implement it right. For example, your sqrt function would run faster if you used Newton's method or the lookup table method. As always there is a trade off between speed and memory.

Good job anyway.
 
Originally posted by PrudensOptimus

/*Object Oriented Programming

How was that code object oriented?
 
Originally posted by dduardo
That is some really messy code. You should look into taking an algorithms class. Your code could run a lot faster if you implement it right. For example, your sqrt function would run faster if you used Newton's method or the lookup table method. As always there is a trade off between speed and memory.

Good job anyway.


There was also a PowerDec function. can estimate anything in the form of a^b.

It looks messy because Physics Forums' format is f****ed up
 
Originally posted by PrudensOptimus

It looks messy because Physics Forums' format is f****ed up

Add this at the beginning [ code ] ((without the spaces of course)), then add this at the end [ /code ] that should fix it.


And you misspelled inaccuracy ;)
Code:
}
	static double Sqrt(double a) {
		//There is really no easy way to find sqrts out of scratch.
		//You can expand it, but as numbers vary, [b]inaccurcy[/b] varies greatly.
		//Thus, my intention is to loop until b*b is about a.
		double b = 0;
		
		while((b*b) <= a) {
			b += 0.0001;
		}
		
		return b;
 
Last edited:
You should really invest some time in learning about computational complexity, and Taylor/Mclaurin series. Any algorithm that generates n digits of precision in more than O(n log n) time is a waste.
 
Java will multiply by 3.14 just as well as it will multiply by 3.14159265358979323846, so you might as well include a more precise value for Pi. Actually, java gives you Math.Pi for this purpose!


Oh, and your ceiling function is wrong: Project3.Ceil(1) == 2. :frown:


But in any case, Prudens was trying to do 'em from scratch; such exercises can be fun. :smile: And then replaced with some researched methods later, if needed.
 
Originally posted by Hurkyl
Java will multiply by 3.14 just as well as it will multiply by 3.14159265358979323846, so you might as well include a more precise value for Pi. Actually, java gives you Math.Pi for this purpose!


Oh, and your ceiling function is wrong: Project3.Ceil(1) == 2. :frown:


But in any case, Prudens was trying to do 'em from scratch; such exercises can be fun. :smile: And then replaced with some researched methods later, if needed.


How's Match.com working for you Hurkl?
 
Code:
/*+++++++++++++++++++++++++++++++++++++++
 *Area under x^c solver.
 *Using nothing but JOptionPane for input
 *Tom Zhang
 *++++++++++++++++++++++++++++++++++++++*/
 
import javax.swing.JOptionPane;

class Test2 {
	public static void main (String[] args) {
         String strs = JOptionPane.showInputDialog("Input b for x^b");
         String strs1 = JOptionPane.showInputDialog("Input a for [a,b]");
         String strs2 = JOptionPane.showInputDialog("Input b for [a,b]");
         String strs3 = JOptionPane.showInputDialog("Input n for n many partitions in [a,b]");
         
         //Convert
         double a,b;
         int c,n;
         a = Double.parseDouble(strs1);
         b = Double.parseDouble(strs2);
         c = Integer.parseInt(strs);
         n = Integer.parseInt(strs3);
         
         System.out.println("+++++++++++++++++++++++++++++++++++++\n" +
                                               "+Area under curves, aka Integral     \n" +
                                               "+++++++++++++++++++++++++++++++++++++\n" +
                                               "\n\nWelcome, ");
         
         //Create an integrand.
         Integrand f = new Integrand();
         System.out.println(f.Eval(a,b,c,n));//evaluate area under y=x in interval [0,10]
                                            //assuming there are 100 partitions
                                                                                                  //the more partition, the more accurate
         
         System.exit(0);
	}
	public static double Power(double a, int c) {

		for(int i = 1;i<c;i++) {
		a *= a;
		}
	
	return a;
	}
}


class Integrand {
int a, b, c;

	public double Eval(double a, double b, int c, int n) {
         double sum = 0.;
                 //Do the integration here
                 for(int i=1;i<=n/*even though suppose to be infinity*/;i++){
                         sum += Test2.Power((a + i*((b-a)/n)),c) * ((b-a)/n); // f(x)dx 500 is n. even though suppose to be infinity 
                 }
         
		return sum;

	}

}

Sample Integral (x^c) solver.
 
  • #10
Take a look at the book "Numerical Recipes." It is available in its entirety for free, online, at www.nr.com.

dduardo is right -- he's not saying your program is messy in format, with spacing and structure -- he's saying it's algorithmically messy (and it is).

Basically, I can see the value in trying to write your own routines for some of these functions as an exercise, but you've written them in an extremely naive (and extremely slow) way. Take a look at Numerical Recipes, it'll blow you away. :smile:

- Warren
 
  • #11
Originally posted by NateTG
You should really invest some time in learning about computational complexity, and Taylor/Mclaurin series. Any algorithm that generates n digits of precision in more than O(n log n) time is a waste.

There is no Maclaurin series for Sqrt, Log, Power, etc...
 
  • #12
There is a MacLauren series for powers:

[tex] a^x = \sum_{i=0}^{\infty} \frac{(x \ln a)^i}{i!}[/tex]

And there is a MacLauren series for [itex]\ln ((1+x)/(1-x))[/itex].
 
  • #13
Originally posted by PrudensOptimus
There is no Maclaurin series for Sqrt, Log, Power, etc...

There are Taylor/Maclaurin series for any function that is infinitely differentiable, and it's even possible to predict the radius of convergance (although that involves complex ananlysis). Just because you haven't seen them doesn't mean they don't exist.

[tex]f(x)=\sum_{i=0}^{\infty}\frac{f^{i'}(a)(x-a)^i}{i!}[/tex]

where [tex]f^{i'}(a)[/tex] is the ith derivative of [tex]f(x)[/tex].
 

Similar threads

Replies
63
Views
6K
  • · Replies 7 ·
Replies
7
Views
2K
  • · Replies 13 ·
Replies
13
Views
4K
Replies
2
Views
3K
Replies
9
Views
2K
  • · Replies 1 ·
Replies
1
Views
3K
  • · Replies 3 ·
Replies
3
Views
3K
  • · Replies 8 ·
Replies
8
Views
3K
  • · Replies 23 ·
Replies
23
Views
3K
  • · Replies 2 ·
Replies
2
Views
2K