Hand written math functions

In summary, the conversation is about a self-written math function project that demonstrates the individual's great math and coding abilities without the use of predefined math functions. The code includes functions for finding the difference, quotient, absolute value, power, sine, square root, logarithm, floor, and ceiling of given numbers. The conversation also includes suggestions for improving the code, such as using algorithms for faster execution. The conversation ends with a discussion about formatting issues on the platform.
  • #1
PrudensOptimus
641
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:
Physics news on Phys.org
  • #2
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.
 
  • #3
Originally posted by PrudensOptimus

/*Object Oriented Programming

How was that code object oriented?
 
  • #4
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
 
  • #5
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:
  • #6
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.
 
  • #7
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.
 
  • #8
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?
 
  • #9
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].
 

1. What are hand written math functions?

Hand written math functions are mathematical equations or expressions that are written by hand, rather than using a computer or calculator. They are commonly used in mathematics and physics to solve problems and demonstrate concepts.

2. Why are hand written math functions important?

Hand written math functions are important because they allow us to understand and visualize mathematical concepts, rather than just relying on technology. They also help us develop problem-solving skills and improve our understanding of mathematical processes.

3. How do I write a hand written math function?

To write a hand written math function, you will need to use mathematical notation, such as symbols and equations, to represent the problem or concept. You can also use diagrams, graphs, and other visual aids to help illustrate your solution.

4. What are some benefits of using hand written math functions?

There are several benefits of using hand written math functions, including improved understanding of mathematical concepts, increased problem-solving skills, and the ability to easily edit and manipulate equations. They also allow for a deeper exploration and analysis of mathematical concepts.

5. Can hand written math functions be used in scientific research?

Yes, hand written math functions are commonly used in scientific research, especially in fields such as mathematics, physics, and engineering. They allow researchers to easily manipulate and solve complex equations and demonstrate their findings visually.

Similar threads

Replies
63
Views
3K
  • Engineering and Comp Sci Homework Help
Replies
7
Views
2K
  • Engineering and Comp Sci Homework Help
Replies
18
Views
1K
  • Programming and Computer Science
2
Replies
36
Views
3K
  • Programming and Computer Science
Replies
5
Views
2K
  • Programming and Computer Science
Replies
1
Views
749
  • Engineering and Comp Sci Homework Help
Replies
4
Views
2K
  • Engineering and Comp Sci Homework Help
Replies
1
Views
1K
  • Programming and Computer Science
Replies
7
Views
2K
  • Programming and Computer Science
Replies
5
Views
1K
Back
Top