Mathematical Operations Without Using Java Math Class - java

I've been making my own class library in Java and I've run into a small annoyance. The library is centered around math. I started with the intention of not using the Java Math Class. Unfortunately, my lack of skill paired with my inability to find a resource online that tackles this problem has resulted in me falling back onto the Java Math Class. Is there a way I can do logarithms without using Math.log?

We could try to use a power series as per: https://math.stackexchange.com/a/61283
For example:
#Test
public void printMathCalculation() {
double libValue = Math.log(100);
double myValue = getLn(100);
System.out.println("Actual: \t" + libValue);
System.out.println("Approximate: \t" + myValue);
}
//Take double to an integer power
private double pow(double num, int power) {
double result = 1;
for(int i = 0; i < power; i++) {
result *= num;
}
return result;
}
//Get natural log
private double getLn(double num) {
int accuracy = 1000;
double sum = 0;
for(int n = 0; n < accuracy; n++) {
double num1 = (1.0/(2*n+1));
double num2 = (num-1)/(num+1);
sum += num1*pow(num2,2*n+1);
}
return 2 * sum;
}
The results I get are:
Actual: 4.605170185988092
Approximate: 4.605170185988078

You should use Math.log
Try this, using simple maths to calculate
public static int toLog2N(int num){
return num>1 ? 1 + toLog2N(num/2) : 0;
}
Its just an example, you should use Math class as it provides different methods like log(double a), log10(double a), log1p(double a). It will make your code more readable and easier to understand.
hope it helps!

Related

How to get precise Math.exp() in j2me?

I am using j2me and I need to get quite precise exp() for values up to 4.
Problem with the j2me is that it's Math library doesn't have pow() and exp() method. To solve this, I just used this method to implement pow():
public static double pow(double num1, double num2) {
double result = 1;
for (int i = 0; i < num2; i++)
result *= num1;
return result;
}
This enabled me to have exp functionality by using setting e as constant (2.718281828459045) and calling pow:
double calculation = (20.386 - (5132.000 / (t + 273.15)));
System.out.println("calc: " + pow(2.71,calculation));
calculation = pow(2.7182818284590452,calculation) * 1.33;
My problem is that result is quite inaccurate, for example if I compare math.exp and my pow method for number 3,75, results are like this:
Pow function returns: 54.5980031309658
Math function returns: 42.52108200006278
So I would need advice, how to implement exp functionality in j2me environment with highest precision possible.
I helped my self with bharath answer in this question: How to get the power of a number in J2ME
Since exp method is just pow, where we use Euler's number for the first argument, I used bharath method:
public double powSqrt(double x, double y)
{
int den = 1024, num = (int)(y*den), iterations = 10;
double n = Double.MAX_VALUE;
while( n >= Double.MAX_VALUE && iterations > 1)
{
n = x;
for( int i=1; i < num; i++ )n*=x;
if( n >= Double.MAX_VALUE )
{
iterations--;
den = (int)(den / 2);
num = (int)(y*den);
}
}
for( int i = 0; i <iterations; i++ )n = Math.sqrt(n);
return n;
}
Method call:
calculation = powSqrt(2.7182818284590452,calculation) * 1.33;
Result is almost as good as Math.pow() method.
PS:
I don't know if this is duplicated thread, if so you can delete it.

Calculating a series

I am trying to write a program that accepts an integer from the user, then it should calculate this series S = 1/2! - 1/3! + 1/4! – 1/5! + .... all the way to 1/x! where x is the integer taken from the user, I already wrote this code to calculate the factorial of x :
import java.util.Scanner;
public class Factorial {
public static void main(String args[]){
Scanner x = new Scanner(System.in);
System.out.println("Enter a number: ");
int number = x.nextInt();
int fact = 1;
for (int i = 1; i <= number; i++){
fact = fact*i;
}
System.out.println("The factorial of "+number+" is "+fact);
x.close();
}
}
but still am not sure how to code the series, any tips would be really appreciated.
Also I am sorry if my code is not organized I don't know how to use stackoverflow tools ;( .
Ideally, what you want is to separate your code into multiple functions, and think logically.
Since you said you didn't want tips, I'll just try to put you on the right track.
Tip 1:
Separate your code into multiple functions
eg.
public static int factorial(int n){
int fact = 1;
for (int i = 1; i <= n; i++){
fact = fact*i;
}
return fact;
}
This allows you to split your code up into manageable chunks. Call each chunk at the appropriate time. This makes your code easier to read and more reusable
Tip 2:
One main class and the other class with functions.
Ideally, you want to create two classes, one which takes input from the user and one which contains all the functions you need. The main class taking the input will create an Object of the other class
public class Factorial{
public static void main(String args[]){
Scanner x = new Scanner(System.in);
System.out.println("Enter a number: ");
int number = x.nextInt();
Series s=new Series(number);
s.print();
x.close();
}
And in Series.java
public class Series{
int output;
int input;
Series(int i){
input=i;
//..here you calculate output
}
public int factorial(int n){
//.... the code
}
public void print(){
System.out.println("The calculation of " + input + " is " + output);
}
}
Tip 3:
Make a nice simple function to calculate the output. Sum up all your factorials over time
for (int i = 2; i <= input; i++) {
//if its even
if(i%2==0)
output = output + 1.0 / factorial(i);
else
output = output - 1.0 / factorial(i);
}
Add the following to your constructor and you'll have a well built Java program
Tip 4:: These sums are going to be decimals, not integers so you need to replace all your ints with doubles
First, you have to compute a sum of terms. The standard pattern is like
double sum = 0;
for (int i = first; i <= last; i++) {
sum += term(i);
}
then remark that
the first term is term(2) = +1/2!
the second term is term(3) = -1/3! = -term(2)/3
the third term is +1/4! = -term(3)/4
etc.
So you'll notice that each term can be easily obtained from the previous one.
This leads to
double sum = 0;
double term = (some value);
for (int i = first; i <= last; i++) {
term = (some expression involving i and previous term);
sum += term;
}
Exercise left as, huh, an exercise ?

how to create an Exp(-x^2) function?

I am using the "think java" book and I am stuck on exercise 7.6. The goal here is to write a function that can find . It gives you a couple hints:
One way to evaluate is
to use the infinite series expansion:
In other words, we need to add up a series of terms where the ith term
is equal to
Here is the code I came up with, but it is horribly wrong (when compared to Math.exp) for anything other than a power of 1. I don't understand why, as far as I can tell the code is correct with the formula from the book. I'm not sure if this is more of a math question or something related to how big of a number double and int can hold, but I am just trying to understand why this doesn't work.
public static void main(String[] args) {
System.out.println("Find exp(-x^2)");
double x = inDouble("Enter x: ");
System.out.println("myexp(" + -x*x + ") = " + gauss(x, 20));
System.out.println("Math.exp(" + -x*x + ") = " + Math.exp(-x*x));
}
public static double gauss(double x, int n) {
x = -x*x;
System.out.println(x);
double exp = 1;
double prevnum = 1;
int prevdenom = 1;
int i = 1;
while (i < n) {
exp = exp + (prevnum*x)/(prevdenom*i);
prevnum = prevnum*x;
prevdenom = prevdenom*i;
i++;
}
return exp;
} // I can't figure out why this is so inacurate, as far as I can tell the math is accurate to what the book says the formula is
public static double inDouble(String string) {
Scanner in = new Scanner (System.in);
System.out.print(string);
return in.nextDouble();
}
I am about to add to the comment on your question. I do this because I feel I have a slightly better implementation.
Your approach
Your approach is to have the function accept two arguments, where the second argument is the number of iterations. This isn't bad, but as #JamesKPolk pointed out, you might have to do some manual searching for an int (or long) that won't overflow
My approach
My approach would use something called the machine epsilon for a data type. The machine epsilon is the smallest number of that type (in your case, double) that is representable as that number. There exists algorithm for determining what that machine epsilon is, if you are not "allowed" to access machine epsilon in the Double class.
There is math behind this:
The series representation for your function is
Since it is alternating series, the error term is the absolute value of the first term you choose not to include (I leave the proof to you).
What this means is that we can have an error-based implementation that doesn't use iterations! The best part is that you could implement it for floats, and data types that are "more" than doubles! I present thus:
public static double gauss(double x)
{
x = -x*x;
double exp = 0, error = 1, numerator = 1, denominator = 1;
double machineEpsilon = 1.0;
// calculate machineEpsilon
while ((1.0 + 0.5 * machineEpsilon) != 1.0)
machineEpsilon = 0.5 * machineEpsilon;
int n = 0; //
// while the error is large enough to be representable in terms of the current data type
while ((error >= machineEpsilon) || (-error <= -machineEpsilon))
{
exp += error;
// calculate the numerator (it is 1 if we just start, but -x times its past value otherwise)
numerator = ((n == 0) ? 1 : -numerator * x);
// calculate the denominator (denominator gets multiplied by n)
denominator *= (n++);
// calculate error
error = numerator/denominator;
}
return exp;
}
Let me know how this works!

Java: double rounding algorithm

I got curious about a rounding algorithm, because in CS we had to emulate an HP35 without using the Math library. We didn't include a rounding algorithm in our final build, but I wanted to do it anyway.
public class Round {
public static void main(String[] args) {
/*
* Rounds by using modulus subtraction
*/
double a = 1.123599;
// Should you port this to another method, you can take this as a parameter
int b = 5;
double accuracy = Math.pow(10, -b);
double remainder = a % accuracy;
if (remainder >= 5 * accuracy / 10) // Divide by ten is important because remainder is smaller than accuracy
a += accuracy;
a -= remainder;
/*
* Removes round off error done by modulus
*/
String string = Double.toString(a);
int index = string.indexOf('.') + b;
string = string.substring(0, index);
a = Double.parseDouble(string);
System.out.println(a);
}
}
Is this a good algorithm, or are there any better ones? I don't care about the ones defined in the Java API, I just wanted to know how it was done.
[EDIT]
Here's the code I came up with after looking over EJP's answer
public class Round {
public static void main(String[] args) {
double a = -1.1234599;
int b = 5;
boolean negative = a < 0;
if (negative) a = -a;
String string = Double.toString(a);
char array[] = string.toCharArray();
int index = string.indexOf('.') + b;
int i = index;
int value;
if (Character.getNumericValue(array[index +1]) >= 5) {
for (; i > 0; i--) {
value = Character.getNumericValue(array[i]);
if (value != -1) {
++value;
String temp = Integer.toString(value)
array[i] = temp.charAt(temp.length()-1);
if (value <= 9) break;
}
}
}
string = "";
for (int j=0; j < index + 1 ; j++) {
string += array[j];
}
a = Double.parseDouble(string);
if (negative) a =-a;
System.out.println(a);
}
}
Floating-point numbers don't have decimal places. They have binary places, and the two are not commensurable. Any attempt to modify a floating-point variable to have a specific number of decimal places is doomed to failure.
You have to do the rounding to a specified number of decimal places after conversion to a decimal radix.
There are a different ways to round numbers. The RoundingMode documentation for Java (introduced in 1.5) should give you a brief introduction to the different methods people use.
I know you said you don't have access to the Math functions, but the simplest rounding you can do is:
public static double round(double d)
{
return Math.floor(d + 0.5);
}
If you don't want to use any Math functions, you could try something like this:
public static double round(double d)
{
return (long)(d + 0.5);
}
Those two probably behave differently in some situations (negative numbers?).

Java - raise Real To Power n^k

I'm having difficulty writing a program to solve this exercise from a Java text book:
Write a method raiseRealToPower that takes a floating-point value x and an integer
k and returns xk. Implement your method so that it can correctly calculate the result
when k is negative, using the relationship
x^(-k) = 1 / x^k.
Use your method to display a table of values of πk for all values of k from –4 to 4.
I didn't done this part with PI, i know that, if my programs starts to work... this is what i done... tell me please, what is wrong.
import acm.program.*;
public class vjezba55 extends ConsoleProgram {
private static final double PI = 3.14159253;
public void run() {
double x = readDouble ("x: ");
double k = readDouble ("k: ");
println ("x^k = " + raiseDoublePower(x,k));
}
/* Method that counts x^k */
private double raiseDoublePower (double x, double k){
if (k >= 0) {
return Math.pow(x, k);
}
else {
double total = 1;
for (int i= 0; i>k; i--) {
total = (double) 1 / x;
}
return total;
}
}
}
Take a look at your loop code. You are just recalculating total from scratch on each iteration, rather than updating the previous result.
I don't understand the part in the question regarding PI, but your method may be much simpler (according to using the relationship x^(-k) = 1 / x^k):
private double raiseDoublePower (double x, double k){
if (k >= 0) {
return Math.pow(x, k);
}
else {
return 1 / Math.pow(x, -k);
}
}

Categories

Resources