calculate double negative exponent - java

I want to know how to calculate this equation in Java considering that the exponent can be negative
equation example:
D_DL=10^((149.874-69.55-26.16 log_10(900)+13.82 log_10(60)+1.115)/([44.9-6.55 log_10(60)]))
Here I'm trying to calculate my exponent
double exposantD = ( Mapldl_s - 69.55 -( 26.16 * Math.log10(_BF_) )+ (13.82 * Math.log10(HB_)) + _ahm_) / (44.9 - (6.55 *Math.log10(HB_)));
I try with this function :
public static double powMyExpo(double base, double exponent) {
double result = 1;
if (exponent == 0) {
return result;
}
if (exponent < 0) {
return 1 / powMyExpo(base, exponent * -1);
}
for (int i = 1; i <= exponent; i++) {
result = result * base;
}
return result;
}
but always result = 1
Thanks

Related

I want to make a function to find the closest value to n such that 32 % n = 0 in Java

I'm trying to make an efficient function that's described in the title of this question. Here is what I have tried, but I'm sure their is a better way. I'm using Java 8
Question: Is their a better way to implement this function that is more efficient?
private static double nearestMod(double n) {
// Check if n already satisfies the condition
if (32 % n == 0) {
return n;
}
// Check if the solution can't be reasonably obtained
if (n > 32) {
return -1;
}
double increment;
int numsAfterDecimalPoint = String.valueOf(n).split("\\.")[1].length();
if (n % 1 == 0) {
// If n is a whole number
increment = 10;
} else {
increment = 1d / Math.pow(10, numsAfterDecimalPoint - 1);
}
double result = Double.MAX_VALUE;
double multiplier = increment == 10 ? 1 : Math.pow(10, numsAfterDecimalPoint);
for (double i = n - increment * multiplier; i < n + increment * multiplier; i += increment / 10d) {
double check = 32 / i;
if (Math.abs(Math.round(check) - check) < increment / 10d && Math.abs(i - n) < Math.abs(result - n)) {
result = i;
}
}
return result;
}
Example:
nearestMod(0.26) should return 0.25

how to make a formula to find the value of D from values in another formula

In my Pulse Wave generator, I need to find the value of cyclePoint (c) from cycleFrequency (f), cycleRange (r), minDutyCycle (m) and dutyCycle d.
Here is a formula that I made that finds the value of dutyCycle (d) from the other value
D = ((c/(f/2))r)+m
I'm not the best at algebra so I probably used the brackets wrong.
Here is my code
public class PulseGenerator extends SquareGenerator {
// constants
public static final double DEF_MIN_DUTY_CYCLE = 0.05;
public static final double DEF_MAX_DUTY_CYCLE = 0.95;
public static final double DEF_CYCLE_FREQ = 2;
public static final double DEF_HOLD_CYCLE = 0;
// instance variables
double minDutyCycle;
double maxDutyCycle;
double cycleFreq;
double holdCycle;
double dutyCycleRange;
boolean setDirection;
// constructor
public PulseGenerator(double amplitude, double frequency, int bitRate,
double duration, double dutyCycle, double minDutyCycle,
double maxDutyCycle, double cycleFreq, double holdCycle) {
super(amplitude, frequency, bitRate, duration, dutyCycle);
// sample data
squareSample = new int[sampleLength];
calculateAmpLimit();
this.dutyCycle = dutyCycle;
waveLength = sampleRate / this.frequency;
this.minDutyCycle = minDutyCycle;
this.maxDutyCycle = maxDutyCycle;
this.cycleFreq = cycleFreq * sampleRate;
this.holdCycle = holdCycle * sampleRate;
dutyCycleRange = this.maxDutyCycle - this.minDutyCycle;
setDirection = false;
}
// one arg cunstructor
public PulseGenerator(double frequency) {
this(AMPLITUDE, frequency, BIT_RATE, DURATION, DEF_DUTY_CYCLE,
DEF_MIN_DUTY_CYCLE, DEF_MAX_DUTY_CYCLE, DEF_CYCLE_FREQ,
DEF_HOLD_CYCLE);
}
// no args constructor
public PulseGenerator() {
this(AMPLITUDE, FREQUENCY, BIT_RATE, DURATION, DEF_DUTY_CYCLE,
DEF_MIN_DUTY_CYCLE, DEF_MAX_DUTY_CYCLE, DEF_CYCLE_FREQ,
DEF_HOLD_CYCLE);
}
// generate waveform method
#Override
public int[] generateWaveForm() {
// define the decimal j
double j = 1;
// define cycle point
// here is where I need to find the value of cycle point
int cyclePoint = (int)((dutyCycle * (cycleFreq / 2) - minDutyCycle) / dutyCycleRange);
System.out.println("Cycle point: " + cyclePoint);
// generate the actual waveform
for (int i = 0; i < sampleLength; i++, j++) {
double waveCycleRatio = waveLength * dutyCycle;
// same as square
// draws the wave
if (j - waveCycleRatio < 0.0) {
finePoint = 1.0;
} else if (j - waveCycleRatio >= 0.0
&& j - waveCycleRatio < 1) {
finePoint = 0 - (j - waveCycleRatio - 0.5) * 2;
} else if (j - waveLength < 0.0) {
finePoint = -1.0;
} else if (j - waveLength >= 0.0) {
finePoint = (j - waveLength - 0.5) * 2;
}
// checks if j is equal to wavelength
if (j == waveLength) {
j = 1;
} else if (j - waveLength > 0.0 && j - waveLength < 1.0) {
j = (j - waveLength);
}
point = (int)(finePoint * ampLimit);
squareSample[i] = point;
if (holdCycle > 0) {
holdCycle--;
} else {
// implementation of formula to find duty cycle
dutyCycle = (cyclePoint / (cycleFreq / 2) * dutyCycleRange)
+ minDutyCycle;
if (cyclePoint < cycleFreq / 2 && !setDirection) {
cyclePoint++;
} else if (cyclePoint >= cycleFreq / 2 && !setDirection) {
cyclePoint--;
setDirection = true;
} else if (cyclePoint > 0 && setDirection) {
cyclePoint--;
} else if (cyclePoint <= 0 && setDirection) {
cyclePoint++;
setDirection = false;
}
}
}
// return the sample data
return squareSample;
}
}
I believe this line is a bit off:
int cyclePoint = (int)((dutyCycle * (cycleFreq / 2) - minDutyCycle) / dutyCycleRange);
and it should be like:
int cyclePoint = (int)((cycleFreq / 2) * (dutyCycle - minDutyCycle) / dutyCycleRange);
This code line:
int cyclePoint = (int)((dutyCycle * (cycleFreq / 2) - minDutyCycle) / dutyCycleRange);
should be replaced with:
int cyclePoint = (int) (((dutyCycle - minDutyCycle) * cycleFreq) / (2 * dutyCycleRange));

Sin approximation using Maclaurin expansion

I'm trying to write own code for calculating approximation of rad angle. I works so far for only a specific range of numbers, but fails for large ones like 500 or so.
Additional subquestion: which is more efficient - calculating powers by Math.pow() or the current way of doing it - only multiplication operators.
private static double sin_range(double rad) {
double sin_rad = rad;
while (sin_rad > 2 * Math.PI) {
sin_rad -= 2 * Math.PI;
}
return sin_rad;
}
private static double approx(double rad, int err) {
double rad_in_range = sin_range(rad);
double sin = rad_in_range, r = rad_in_range;
int previous = 1, factorial = 1;
for (int i = 0; i < err; i++) {
factorial = (factorial * (previous + 1) * (previous + 2));
r *= rad * rad;
if ((i & 1) == 0) { //even
sin -= r / factorial;
} else { //odd
sin += r / factorial;
}
previous += 2;
}
return sin;
}
public static void main(String[] args) {
double approximated = approx(15, 5);
System.out.println(approximated + " = " + Math.sin(15));
}

Return how many terms are necessary entering a level of precision, e.g .001, to come within the specified precision of the value of PI?

Problem: Interactively enter a level of precision, e.g., .001, and then report how many terms are necessary for each of these estimates to come within the specified precision of the value of pi.
My Solution So Far:
Current result does not terminate. The PIEstimator class driver is given. The problem lies inside the PIEstimates class. Some specific questions that I have:
How do you calculate Wallis PI and Leibniz PI in code? The ways for calculating each arithmetically for Wallis is:
pi/4 = (2/3)(4/3)(4/5)(6/5)(6/7)(8/7)(8/9)*...
and for Leibniz:
pi/4 = (1 - 1/3 + 1/5 - 1/7 + 1/9 ...)
Is the current logic of doing this code correct so far? Using a while loop to check if the respective PI calculation is within the limits, with a for loop inside continuing to run until the while requirements are met. Then there is a count that returns the number of times the loop repeated.
For .001, for example, how many terms does it take for each of these formulas to reach a value between 3.14059.. and 3.14259...
import java.util.Scanner;
public class PiEstimator {
public static void main(String[] args) {
System.out.println("Wallis vs Leibnitz:");
System.out.println("Terms needed to estimate pi");
System.out.println("Enter precision sought");
Scanner scan = new Scanner(System.in);
double tolerance = scan.nextDouble();
PiEstimates e = new PiEstimates(tolerance);
System.out.println("Wallis: " + e.wallisEstimate());
System.out.println("Leibnitz: " + e.leibnitzEstimate());
}
}
public class PiEstimates {
double n = 0.0;
double upperLim = 0;
double lowerLim = 0;
public PiEstimates(double tolerance) {
n = tolerance;
upperLim = Math.PI+n;
lowerLim = Math.PI-n;
}
public double wallisEstimate() {
double wallisPi = 4;
int count = 0;
while(wallisPi > upperLim || wallisPi < lowerLim) {
for (int i = 3; i <= n + 2; i += 2) {
wallisPi = wallisPi * ((i - 1) / i) * ((i + 1) / i);
}
count++;
}
return count;
}
public double leibnitzEstimate() {
int b = 1;
double leibnizPi = 0;
int count = 0;
while(leibnizPi > upperLim || leibnizPi < lowerLim) {
for (int i = 1; i < 1000; i += 2) {
leibnizPi += (4/i - 4/i+2);
}
b = -b;
count++;
}
return count;
}
}
At least one mistake in wallisEstimate
for (int i = 3; i <= n + 2; i += 2) {
should be count instead of n:
for (int i = 3; i <= count + 2; i += 2) {
... but still then the algorithm is wrong. This would be better:
public double wallisEstimate() {
double wallisPi = 4;
int count = 0;
int i = 3;
while(wallisPi > upperLim || wallisPi < lowerLim) {
wallisPi = wallisPi * ((i - 1) / i) * ((i + 1) / i);
count++;
i += 2;
}
return count;
}
Similarly, for the Leibniz function:
public double leibnitzEstimate() {
double leibnizPi = 0;
int count = 0;
int i = 1;
while(leibnizPi > upperLim || leibnizPi < lowerLim) {
leibnizPi += (4/i - 4/i+2);
count++;
i += 4;
}
return count;
}
For Leibnitz, I think the inner loop should only run count number of times:
for (int i = 1; i < count; i += 2) {
leibnizPi += (4/i - 4/i+2);
}
If it runs 1000 times every time you can't know when pi was in range.
If the while loops don't terminate, then they don't approach PI.
Wallis: pi/4 = (2/3)(4/3)(4/5)(6/5)(6/7)(8/7)(8/9)*...
The while loop would restart the for loop at i = 3 which would keep adding the same sequence of terms, rather than progressing along with the pattern.
Here's a draft of an alternative solution (no pun intended) based on the pattern of terms.
As you see, the numerators repeat, except for the 2. The divisors repeat aswell, but offset from the numerators: they increment in an alternating fashion.
This way you can actually count each individual terms, instead of pairs of them.
public double wallisEstimate() {
double wallisPi = 1;
int count = 0;
double numerator = 2;
double divisor = 3;
while(wallisPi > upperLim || wallisPi < lowerLim) {
wallisPi *= numerator / divisor;
if ( count++ & 1 == 0 )
numerator+=2;
else
divisor+=2;
}
return count;
}
There is one more change to make, and that is in the initialisation of upperLim and lowerLim. The algorithm approaches PI/2, so:
upperLim = (Math.PI + tolerance)/2;
lowerLim = (Math.PI - tolerance)/2;
Leibniz: pi/4 = (1 - 1/3 + 1/5 - 1/7 + 1/9 ...)
Here the for loop is also unwanted: at best, you will be counting increments of 2000 terms at a time.
The pattern becomes obvious if you write it like this:
1/1 - 1/3 + 1/5 - 1/7 ...
The divisor increments by 2 for every next term.
public double leibnitzEstimate() {
double leibnizPi = 0;
int divisor = 1;
int count = 0;
while(leibnizPi > upperLim || leibnizPi < lowerLim) {
leibnizPi += 1.0 / divisor;
divisor = -( divisor + 2 );
count++;
}
return count;
}
The update of leibnizPi can also be written like this:
leibnizPi += sign * 1.0 / divisor;
divisor += 2;
sign = -sign;
which is more clear, takes one more variable and one more instruction.
An update to the upperLim and lowerLim must be made here aswell: the algorithm approaches PI/4 (different from Leibniz!), so:
upperLim = (Math.PI + tolerance)/4;
lowerLim = (Math.PI - tolerance)/4;

how to get exponents without using the math.pow for java

This is my program
// ************************************************************
// PowersOf2.java
//
// Print out as many powers of 2 as the user requests
//
// ************************************************************
import java.util.Scanner;
public class PowersOf2 {
public static void main(String[] args)
{
int numPowersOf2; //How many powers of 2 to compute
int nextPowerOf2 = 1; //Current power of 2
int exponent= 1;
double x;
//Exponent for current power of 2 -- this
//also serves as a counter for the loop Scanner
Scanner scan = new Scanner(System.in);
System.out.println("How many powers of 2 would you like printed?");
numPowersOf2 = scan.nextInt();
System.out.println ("There will be " + numPowersOf2 + " powers of 2 printed");
//initialize exponent -- the first thing printed is 2 to the what?
while( exponent <= numPowersOf2)
{
double x1 = Math.pow(2, exponent);
System.out.println("2^" + exponent + " = " + x1);
exponent++;
}
//print out current power of 2
//find next power of 2 -- how do you get this from the last one?
//increment exponent
}
}
The thing is that I am not allowed to use the math.pow method, I need to find another way to get the correct answer in the while loop.
Powers of 2 can simply be computed by Bit Shift Operators
int exponent = ...
int powerOf2 = 1 << exponent;
Even for the more general form, you should not compute an exponent by "multiplying n times". Instead, you could do Exponentiation by squaring
Here is a post that allows both negative/positive power calculations.
https://stackoverflow.com/a/23003962/3538289
Function to handle +/- exponents with O(log(n)) complexity.
double power(double x, int n){
if(n==0)
return 1;
if(n<0){
x = 1.0/x;
n = -n;
}
double ret = power(x,n/2);
ret = ret * ret;
if(n%2!=0)
ret = ret * x;
return ret;
}
You could implement your own power function.
The complexity of the power function depends on your requirements and constraints.
For example, you may constraint exponents to be only positive integer.
Here's an example of power function:
public static double power(double base, int exponent) {
double ans = 1;
if (exponent != 0) {
int absExponent = exponent > 0 ? exponent : (-1) * exponent;
for (int i = 1; i <= absExponent; i++) {
ans *= base;
}
if (exponent < 0) {
// For negative exponent, must invert
ans = 1.0 / ans;
}
} else {
// exponent is 0
ans = 1;
}
return ans;
}
If there are no performance constraints you can do:
double x1=1;
for(int i=1;i<=numPowersOf2;i++){
x1 =* 2
}
You can try to do this based on this explanation:
public double myPow(double x, int n) {
if(n < 0) {
if(n == Integer.MIN_VALUE) {
n = (n+1)*(-1);
return 1.0/(myPow(x*x, n));
}
n = n*(-1);
return (double)1.0/myPow(x, n);
}
double y = 1;
while(n > 0) {
if(n%2 == 0) {
x = x*x;
}
else {
y = y*x;
x = x*x;
}
n = n/2;
}
return y;
}
It's unclear whether your comment about using a loop is a desire or a requirement. If it's just a desire there is a math identity you can use that doesn't rely on Math.Pow.
xy = ey∙ln(x)
In Java this would look like
public static double myPow(double x, double y){
return Math.exp(y*Math.log(x));
}
If you really need a loop, you can use something like the following
public static double myPow(double b, int e) {
if (e < 0) {
b = 1 / b;
e = -e;
}
double pow = 1.0;
double intermediate = b;
boolean fin = false;
while (e != 0) {
if (e % 2 == 0) {
intermediate *= intermediate;
fin = true;
} else {
pow *= intermediate;
intermediate = b;
fin = false;
}
e >>= 1;
}
return pow * (fin ? intermediate : 1.0);
}
// Set the variables
int numPowersOf2; //How many powers of 2 to compute
int nextPowerOf2 = 1; //Current power of 2
int exponent = 0;
/* User input here */
// Loop and print results
do
{
System.out.println ("2^" + exponent + " = " + nextPowerOf2);
nextPowerOf2 = nextPowerOf2*2;
exponent ++;
}
while (exponent < numPowersOf2);
here is how I managed without using "myPow(x,n)", but by making use of "while". (I've only been learning Java for 2 weeks so excuse, if the code is a bit lumpy :)
String base ="";
String exp ="";
BufferedReader value = new BufferedReader (new InputStreamReader(System.in));
try {System.out.print("enter the base number: ");
base = value.readLine();
System.out.print("enter the exponent: ");
exp = value.readLine(); }
catch(IOException e){System.out.print("error");}
int x = Integer.valueOf(base);
int n = Integer.valueOf(exp);
int y=x;
int m=1;
while(m<n+1) {
System.out.println(x+"^"+m+"= "+y);
y=y*x;
m++;
}
To implement pow function without using built-in Math.pow(), we can use the below recursive way to implement it. To optimize the runtime, we can store the result of power(a, b/2) and reuse it depending on the number of times is even or odd.
static float power(float a, int b)
{
float temp;
if( b == 0)
return 1;
temp = power(a, b/2);
// if even times
if (b%2 == 0)
return temp*temp;
else // if odd times
{
if(b > 0)
return a * temp * temp;
else // if negetive i.e. 3 ^ (-2)
return (temp * temp) / a;
}
}
I know this answer is very late, but there's a very simple solution you can use if you are allowed to have variables that store the base and the exponent.
public class trythis {
public static void main(String[] args) {
int b = 2;
int p = 5;
int r = 1;
for (int i = 1; i <= p; i++) {
r *= b;
}
System.out.println(r);
}
}
This will work with positive and negative bases, but not with negative powers.
To get the exponential value without using Math.pow() you can use a loop:
As long as the count is less than b (your power), your loop will have an
additional "* a" to it. Mathematically, it is the same as having a Math.pow()
while (count <=b){
a= a* a;
}
Try this simple code:
public static int exponent(int base, int power) {
int answer = 1;
for(int i = 0; i < power; i++) {
answer *= base;
}
return answer;
}

Categories