I'm using binary search to write a simple square root calculator that takes in doubles in Java. When I tried to test my code by printing out the answer in the main function, however, nothing got printed out in the terminal. I also got errors Possible lossy conversion from double to float......
Here is my code:
public class MyMath{
public static double sqrt(double n){
double u = 1;
double l = 0;
float m = (u + l) / 2;
double norm_input = 1;
float acc = 0.00000000001;
double answer = 0;
if ((n > 0) && (n < 1)){
if ((m * m) < n){
l = m;
}else{
u = m;
}
answer = (u + l) / 2;
return answer;
}else{
int count = 0;
while (n > 1){
n = n / 4;
norm_input = norm_input * 2;
count++;
}
while ((u - l) > acc){
if ((m * m) < n){
l = m;
}else{
u = m;
}
}
answer = (u + l) / 2 * norm_input;
return answer;
}
}
public static void main(String[] args){
double a = new MyMath().sqrt(4);
System.out.println(a);
}
}
It is stuck in infinite loop in second while condition, that's the reason it is not printing values to console.
float m = (u + l) / 2;
Here you have to type cast into float because when two datatype variable participated in division the result would be in higher data type.
float acc = 0.00000000001;
Here also you have type cast because by default java treats a decimal point value as Double.
while ((u - l) > acc){
if ((m * m) < n){
l = m;
}
}
and your code here is going to infinite loop .
Related
𝜋 = √12 × (1/1x30 - 1/3x31 + 1/5x32 - 1/7x33 +........)
I am trying to solve this equation using java but I do not know how to make subtract when the power is odd.
public static double calculatePiInnitial(int i){
double sum = 0;
for (int n=0; n<=i;n++){
for(int k = 1; k<=k; k =+ 2) {
if (n % 2 == 0)
sum += 1/k*Math.pow(3, n);
else
sum += -1/k* Math.pow(3, n);
}
}
System.out.println(sum);
final double SQRT_12 = Math.sqrt(12) ;
double Pi = SQRT_12 * sum;
return Pi ;
}
There are a couple of issues with the method that you have posted.
Firstly, you are attempting to initialize a variable in out update expression n++ int k=0, which is not valid syntax.
Even if the syntax allowed this, the update expression in not executed until after the body of the for loop, which means that k would not be accessible within the loop.
You should instead declare k together with n in you initialize expression. (also k should be initialized as 1 not 0)
Secondly, you are using i as the exponent when it should be n.
With these changes, you method becomes:
public static double calculatePiInnitial(int i){
double sum = 0;
for (int n=0, k = 1; n<=i; n++, k+=2){
if(n%2 == 0)
sum += 1/(k * Math.pow(3,n));
else
sum -= 1/(k * Math.pow(3,n));
}
System.out.println(sum);
final double SQRT_12 = Math.sqrt(12) ;
double Pi = SQRT_12 * sum;
return Pi ;
}
If you want to do this in two for loops , this is how it can be done. Here the inner for loop iterates only once.
public static double calculatePiInitial(int i){
double sum = 0;
for (int n=0; n<=i;n++){
for(int k = n*2+1; k < n*2+2; k++) {
if (n % 2 == 0)
sum += 1/(k*Math.pow(3, n));
else
sum += -1/(k* Math.pow(3, n));
}
}
System.out.println(sum);
final double SQRT_12 = Math.sqrt(12) ;
double Pi = SQRT_12 * sum;
return Pi ;
}
Hope it helps
I'm quite good enough with Java syntax and just decided to put it to work by creating a code for sine based on an algorithm I created earlier. I know Math.sin helps you evaluate sine but I just for the fun, decided to go on an create my own source code.
However, angles between 60° and 120° and also between 240° and 300° give wrong answers and I have no idea why. Could someone please help me find the error? I've tried everything to detect it but failed.
import java.util.Scanner;
public class Sine {
public static void main(String[] args) {
// This code solves sine according yo the general expansion of sine
// sin x = x - x³/3! +x^5/5! - x^7/7! +...
Scanner scanner = new Scanner(System.in);
double answer = scanner.nextDouble();
scanner.close();
answer = simplify(answer);
answer = converttoradian(answer);
answer = continued(answer);
System.out.println(answer);
}
// This Makes all the angles that are more than 360
// To become less than 360 and Generates the simplified
// Angles for obtuse and reflex angles
static double simplify(double x) {
if (x >= 360) {
x = x - 360;
return simplify(x);
}
else if (x <= -360) {
x = x + 360;
return simplify(x);
}
else if (x > 90 && x <= 270) {
x = 180 - x;
return x;
}
else if (x >= 270) {
x = x - 360;
return x;
}
else if (x <= -90 && x > -270) {
x = -x - 180;
return x;
}
else if (x <= -270) {
x = x + 360;
return x;
}
else {
return x;
}
}
// Simple enough and explains itself
// Converts the angles to radian
static double converttoradian(double d) {
d *= Math.PI;
d /= 180.0;
return d;
}
// This Method about to open generates each term and adds them together
// The number of terms solved in this case is 33
static double continued(double d) {
double answer = 0.0;
int index = 1;
double one = d;
for (int i = 0; i < 33; i++) {
double result = 0.0;
for (int x = 1; x < index; x++) {
d = d * one;
}
long here = factorial(index);
result = d / here;
if ((index - 1) % 4 == 0) {
answer = answer + result;
index = index + 2;
}
else {
answer = answer - result;
index = index + 2;
}
}
return answer;
}
// Evaluates factorials
static long factorial(int n) {
long one = 1;
long m = (long) n;
if (m == 0 || m == 1) {
one = 1;
return one;
}
else {
while (m > 1) {
one *= m;
m--;
}
return one;
}
}
}
There was a lot going on in your program and some unnecessary code. You were on the right track, though. I made some changes to simplify the calculations. You should be able to follow them.
Specifically.
Alternate the sign. Start out with sign = 1, then set sign = -sign for subsequent terms.
For the denominator and factorial, I just used the for loop, starting at 1 and incrementing by 2 to get 1,3,5,7
For powers of the same value, I just multiplied d by a dSquared constant to achieve the same.
I rewrote the factorial to make it simpler.
To reduce large values of d I just used the remainder operator to get them less than 360.
I added some print statements to show calculation progress and to ensure things were working correctly.
And finally, the maximum factorial that will fit in a long is 20!. After that they turn negative due to overflow. So the number of terms needed to be reduced.
public class Sine {
public static void main(String[] args) {
// This code solves sine according yo the general expansion of sine
// sin x = x - x³/3! +x^5/5! - x^7/7! +...
for (double degrees = 0; degrees < 700; degrees += 17) {
double simplified_degrees = simplify(degrees);
System.out.println("simplified_degrees = " + simplified_degrees);
double radians = converttoradian(simplified_degrees);
System.out.println("radians = " + radians);
double sin = continued(radians);
System.out.println(sin);
System.out.println(Math.sin(radians));
System.out.println("------------------------------------------");
}
}
// This Makes all the angles that are more than 360
// To become less than 360 and Generates the simplified
// Angles for obtuse and reflex angles
static double simplify(double x) {
x = x % 360;
return x;
}
// Simple enough and explains itself
// Converts the angles to radian
static double converttoradian(double d) {
return Math.PI / 180. * d;
}
// This Method about to open generates each term and adds them together
// The number of terms solved in this case is 33
static double continued(double d) {
double result = 0;
double sign = 1;
double dSquared = d * d;
int pow = 1;
for (int pow = 1; pow < 21; pow += 2) {
long fact = factorial(pow);
System.out.println("d = " + d + ", fact = " + fact + ", pow = " + pow
+ ", sign = " + sign);
result = result + (d / fact) * sign;
d *= dSquared; // effective powers 3, 5, 7,9
sign = -sign; // alternate sign for every other term
}
return result;
}
// Evaluates factorials
static long factorial(int n) {
if (n == 0 || n == 1) {
return 1;
}
long fact = 1;
for (long i = 2; i <= n; i++) {
fact *= i;
}
return fact;
}
}
I used method a that counts the amount of possible choices for getting like number 10 with numbers that are from 0 to 6. Problem is that it just takes too much time when x is like 50 or something. I just need some tips what I should do to make this faster.
Code
public static int count(int x) {
if (x < 0) {
return 0;
}
if (x == 0) {
return 1;
}
int result = 0;
for (int i = 1; i <= 6; i++) {
result += count(x - i);
}
return result;
}
This is a variation on Fibonacci except it is the sum of the last six values instead.
You can use a plain loop which will be faster than memorisation (the first time)
public static long count(int x) {
long a=0, b=0, c=0, d=0, e=0, f=1;
while(x-- > 0) {
long sum = a + b + c + d + e + f;
a = b; b = c; c = d; d = e; e = f;
f = sum;
}
return f;
}
If you call this repeatedly you may as well store all the values in the int range which is likely to be less than 30 the first time and retrieve these values after that.
Given a float number 7.64, convert it into the string WITHOUT using any inbuilt function/library.
This problem is easy in java . As + operator is overloaded for strings .We can do
class Float2String
{
public static void main(String[] args)
{
float f=7.64f;
String result;
result=""+f;
System.out.println(result);
}
}
But in c as i try to do so ..
int main()
{
float f =2.44;
int i, j = 0;
i = (int) f;
f = f - i;
while(f > 0) {
f *= 10;
j = (j*10) + (int) f;
f = f - (int) f;
}
//now make itoa() to convert i and j to strings .
return 0;
}
Here problem is that floating point error begin to sneak into as while loop goes and j is left with incorrect decimal part .
for example in above case value of f varies like
So how to do this problem in c or C++ .
The sudden jump to an entirely wrong value is caused by j overflowing its int. You could use an unsigned long.
Thel loop will probably not reach 0 however, due to the fact, that floating point numbers are just an approximations of a sum of (negative) powers of 2. Such sums will not decrease when multiplying by 10 and then subtracting the integer part.
The best way would be having a fixed number of digits, multiplying with 10n and then chopping trailing zeroes.
The solution is to print f with the precision (=number of digits) supported by float.
int main()
{
float f =2.44;
int i, len;
char str[100];
i = (int) f;
itoa(i, str, 10);
len = strlen(str);
str[len] = '.';
f = f - i;
while(len <= 6) {
len++;
f *= 10;
str[len] = '0' + (int)f;
f = f - (int) f;
}
str[len + 1] = '\0';
/* Remove trailing zeroes and decimal points. */
for (;len > 0 && (str[len] == '0' || str[len] == '.'); --len) {
if (str[len] == '.') {
str[len] = '\0';
break;
}
str[len] = '\0';
}
printf("%s", str);
return 0;
}
Apart from specifying the number of decimal places, the other way to calculate the decimal value taking into account floating point inaccuracies is to use FLT_EPSILON (or DBL_EPSILON) defined in float.h.
FLT_EPSILON is the difference between 1.0 and the minimum float value greater than 1.0
#include<stdio.h>
#include<float.h>
int main()
{
float origf = 2.44;
float f = origf, newf = 0.0;
int i, j = 0;
int powerOfTen = 1;
i = (int) f;
f = f - i;
do
{
f *= 10;
powerOfTen *= 10;
j = j * 10 + (int)f;
f = f - (int) f;
newf = i + (float)j/ powerOfTen;
} while ((origf + FLT_EPSILON) > newf && newf > (origf - FLT_EPSILON));
printf("%d %d\n", i, j);
return 0;
}
The question here would be to get the sum of powers (m^0 + m^1 + m^2 + m^3.... + m^n) using only FOR loops. Meaning, not using any other loops as well as Math.pow();
Is it even possible? So far, I am only able to work around getting m^n, but not the rest.
public static void main(String[] args){
Scanner scn = new Scanner(System.in);
int total = 1;
System.out.print("Enter value of m: ");
int m = scn.nextInt();
System.out.print("Enter value of n: ");
int n = scn.nextInt();
for (int i = 1; i <= n; i++){
total * m;
}
System.out.print(total);
}
Let's say m =8; and n = 4;
i gives me '1,2,3,4' which is what I need, but I am unable to power m ^ i.
Would be nice if someone could guide me into how it could be done, can't seem to progress onwards as I have limited knowledge in Java.
Thanks in advance!
You might want to rewrite it like this :
m^0 + m^1 + m^2 + m^3.... + m^n = 1 + m * (1 + m * (1 + m * (.... ) ) )
And you do it in a single for loop.
This should do the job (see explanations in comments):
public long count(long m, int pow) {
long result = 1;
for(int i = 0;i<pow; i++) {
result*=m +1;
}
return result;
}
You can nest loops. Use one to compute the powers and another to sum them.
You can do below:
int mul = 1;
total = 1;
for(int i=1;i<=n;i++) {
mul *= m;
total += mul;
}
System.out.println(total);
You can use a single loop which is O(N) instead of nested loops which is O(N^2)
long total = 1, power = m
for (int i = 1; i <= n; i++){
total += power;
power *= m;
}
System.out.print(total);
You can also use the formula for geometric series:
Sum[i = k..k+n](a^i) = (a^k - a^(k+n+1)) / (1 - a)
= a^k * (1 - a^(n+1)) / (1 - a)
With this, the implementation can be done in a single for loop (or 2 simple for loop): either with O(n) simple looping, or with O(log n) exponentiation by squaring.
However, the drawback is that the data type must be able to hold at least (1 - a^(n+1)), while summing up normally only requires the result to fit in the data type.
This is the solution :
for(int i=0;i<n;i++){
temp=1;
for(int j=0;j<=i;j++){
temp *= m;
}
total += temp;
}
System.out.println(total+1);
You can easily calculate powers using your own pow function, something like:
private static long power(int a, int b) {
if (b < 0) {
throw new UnsupportedOperationException("Negative powers not supported.");
}
if (b == 0) {
return 1;
}
if (b == 1) {
return a;
}
return a * power(a, b - 1);
}
Then simply loop over all the values and add them up:
long out = 0;
for (int i = 0; i <= n; ++i) {
out += power(m, i);
}
System.out.println(out);
I would add that this is a classic dynamic programming problem as m^n is m * m^(n-1). I would therefore add caching of previously calculated powers so that you don't have to recalculate.
private static Map<Integer, Long> powers;
public static void main(String args[]) {
int m = 4;
int n = 4;
powers = new HashMap<>();
long out = 0;
for (int i = 0; i <= n; ++i) {
out += power(m, i);
}
System.out.println(out);
System.out.println(powers);
}
private static long power(int a, int b) {
if (b < 0) {
throw new UnsupportedOperationException("Negative powers not supported.");
}
if (b == 0) {
return 1;
}
if (b == 1) {
return a;
}
Long power = powers.get(b);
if (power == null) {
power = a * power(a, b - 1);
powers.put(b, power);
}
return power;
}
This caches calculated values so that you only calculate the next multiple each time.