When writing a method in java, I noticed that these two functions return the same value.
// Riemann-Siegel theta function using the approximation by the Stirling series
public static double theta (double t) {
return (t/2.0 * StrictMath.log(t/2.0/StrictMath.PI) - t/2.0
- StrictMath.PI/8.0 + 1.0/48.0/t + 7.0/5760.0/t/t/t);
}
// Riemann-Siegel theta function using the approximation by the Stirling series
public static double theta2 (double t) {
return (t/2.0 * Math.log(t/(2.0*Math.PI)) - t/2.0
- Math.PI/8.0 + 1.0/(48.0*Math.pow(t, 1)) + 7.0/(5760*Math.pow(t, 3)));
}
What is
7.0/5760.0/t/t/t
doing? Why is this the same as 7.0/(5760*t^3)?
the expression 7.0/5760.0/t1/t2/t3 will be computed from L-R.
like-
r=(7.0/5760.0)
r1=(result/t1)
r2=(r1/t2)
r3=(r2/t3)
and r3 is your final result
if you have expression like 8/2*2*2 it will be calculated as same i've explained earlier but in 8/2*(2*2) expression (2*2) will be calculated first because perathesis has higher priority then /.
it is also aplly in case of math.pow() function because functions also have the higher priority the operators.
Related
I am trying to have some fun by converting some java into c#, I have the following code from java.
public void calculate() {
UnivariateFunction forceBalance = (double x) -> {
return Mu - k1 * fcu * b * x * (d - k2 * x);
};
BrentSolver biSolver = new BrentSolver(1e-6);
x = biSolver.solve(1000, forceBalance, 0, d / 2, 1);
As = Mu / (gamma_r * fy * (d - k2 * x));
}
No all i can find in c# is that seems to solve this MathNet.Numerics as this contains RootFinding.Brent.FindRoot.
I found other stuff that could solve this however I do not have $900.
Here is what i have come up with however i think I might be missing something as my knowledge regarding delegates isn't the best.
class Program
{
public static double Mu = 100e6;
public static double K1 = 0.45 * (1 - (Math.Sqrt(fcu) / 52.5));
public static double fcu = 30.00;
public static double b = 300.00;
//public static double c = 0.00;
public static double d = 500.00;
public static double k2 = (Math.Pow(2 - Math.Sqrt(fcu) / 17.5, 2) + 2) / (4 * (3 - (Math.Sqrt(fcu) / 17.5)));
static void Main(string[] args)
{
Calculate();
}
public static void Calculate()
{
Func<double, double> abc = x => Mu - K1 * fcu * b * x * (d - k2 * x);
var a = MathNet.Numerics.RootFinding.Brent.FindRoot(abc, 0, 10000, 1e-6);
Console.WriteLine();
Console.ReadLine();
}
}
Running this gives me the following error: failed, exceeded the number of iterations allowed or there is no root within the provided bounds.'
Now i am assuming that this is because the func isn't resolving x.
Am i missing something?
Also please take note that this is way above my skill level but I am trying to improve.
Input Values
Firstly if your question is about input values, look at the answer posted by soton. You may be using the wrong FindRoot input values. Brent Math.Net.
double FindRoot(Func<double, double> f, double lowerBound, double upperBound, double accuracy, int maxIterations)
Delegates
Now, with your question I believe you are asking about how delegates are handled in C# vs Java. (I won't spoil your fun).
A delegate is the placeholder for a method which matches a specified signature (a reference to a method).
The following is an example of a variable which matches the delegate type of Func<int, bool> meaning it accepts an integer (x) as a parameter and return a boolean.
The way this example is declared (with an anonymous method body) is known as a Lambda Expression.
Func<int, bool> greaterThanZero = (int x) =>
{
if (x > 0)
return true;
else
return false;
};
Here is the same again, but the delegate variable is assigned from a method declaration.
Func<int, bool> greaterThanZero = SomeGreaterThanZeroMethod;
How do we call a delegate? We Invoke it! e.g.
bool isGreater = greaterThanZero(5); // should be true
bool isGreater = greaterThanZero.Invoke(-1); // should be false
In many situations you will want to make sure the method body is not null e.g.
bool isGreater = false;
if (greaterThanZero != null)
isGreater = greaterThanZero.Invoke(-1);
Or using the fancy new Null-Conditional Operator (?)
bool isGreater = greaterThanZero?.Invoke(-1);
There is more here than you could possibly sum up in an answer. Some resources:
https://www.tutorialspoint.com/csharp/csharp_delegates.htm
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/statements-expressions-operators/lambda-expressions
Your isssue is neither caused by MathNet Numerics implementation of Brent method nor by improper delegates usage. You get this error because there are both roots in fact on the interval provided and evaluation of the given function for both interval ends results in positive numbers i.e. 100000000 and 162453965327 while Brent method requires them to differ in sign. Actual roots for this particular equations are about in 51.8 and 1057.15 so your input interval should contain a point between these two.
To be honest I am a bit surprised why Java implementation works for this set of parameters. Are you sure you have not mistyped anything during conversion?
I am working with a cos value which is represented in double. So my bounds are between -1.0 and 1.0, however for my work I am simply ignoring all negative variables.
Now I'd like to get the decimal number of this double number (sorry I couldn't find the literature term of this operation)
Basically with examples:
Assume that input is 0.12 then this could be written as 1.2 * 10^-1, what I am expecting to get is just the part where it is 10^-1
Another example is 0.00351, which can be written as 3.51 * 10^-3, so the expected result is 10^-3
I have developed this algorithm below but it's kind of quick and dirty. I was wondering whether is there any mathematical trick to avoid using a loop.
double result = 1;
while (input < 1.0) {
input *= 10.0;
result /= 10.0;
}
Also the above doesn't handle if input is 0.
I am using Java for coding if that helps.
It appears you are looking for the base 10 exponent of the number - use Math.log10 to do this
Math.log10(input)
e.g.
log10(100) = 2
log10(1e-5) = -5
etc.
You'll need to remember the base you've used (10 in this case)
public class Tester {
public static double lowbase(double v) {
return Math.pow(10, Math.floor(Math.log10(Math.abs(v))));
}
public static void main(String [] args){
System.out.println(lowbase(0.12));
System.out.println(lowbase(0.00351));
System.out.println(lowbase(0));
System.out.println(lowbase(-1));
}
}
Gives:
0.1
0.001
0.0
1.0
The abs is for handling the negative numbers, you may fiddle with that for a different take on negatives.
In case you are actually looking for strings such as "10^-2" (as you said that the expected result would be in this format).
public String getCientific(double input){
int exp;
exp = (int) java.lang.Math.floor(java.lang.Math.log10(input));
return "10^" + exp;
}
I have a method that calculates the average
Note class:
private Double moyenneFinale;
#Column(name = "moyenne_finale")
public Double getMoyenneFinale() {
return this.moyenneFinale;
}
public void setMoyenneFinale(Double moyenneFinale) {
this.moyenneFinale = moyenneFinale;
}
Class calBean
private double result;
public double moyenneFinale;
public calNote {
result=0.0
result= ((100 * 20)/100)/45;
moyenneFinale=result;
note.setMoyenneFinale(moyenneFinale);
}
//getter and setter
the result should be 0.44
but recorded in the database given value is 0.0
if I make +1 it will be 1.0
All the numeric literals at ((100 * 20)/100)/45 are integers so each operation performs integer arithmetic instead floating pointer arithmetic and finally the result is cast to double at the assignation operation.
You should change at least one of your literals to 100.0, 20.0, 45.0, ...
In line
result= ((100 * 20)/100)/45;
you are using operator / on integers. When used on integers, operator / behaves as "DIV" (resulting integer). Examples: 10/4=2, but 10.0/4=2.5, 10/4.0=2.5, 10.0/4.0=2.5.
Options are:
To set numbers as 100.0, 20.0, 100.0 and 45.0. (It is enough to set just first one to 100.0).
result= ((100.0 * 20)/100)/45;
To use casting on numbers. (double)100.
result= (((double)100 * 20)/100)/45;
Or to add 1.0* before equation;
result= 1.0*((100 * 20)/100)/45;
Tho, first method is best in your case, second and third are useful if you are given integers x, y, z, t and your result is ((x * y)/z)/t;
I'm trying to make a program in Java to calculate the formula for the Ricker wavelet:
But the results are not matching to the real ones.
This is what I'm using:
private static double rickerWavelet(double t, double f){
double p = (Math.pow(Math.PI, 2))*(Math.pow(f, 2))*(Math.pow(t, 2));
double lnRicker = 1 - (2 * p) * Math.exp(-p);
return lnRicker;
}
Am I using the Math functions wrongly?
To match the formula,
double lnRicker = 1 - (2 * p) * Math.exp(-p);
needs to be
double lnRicker = (1 - (2 * p)) * Math.exp(-p);
Since * has higher operator precedence than -, in your expression the multiplication of (2 * p) with Math.exp(-p) will be done first, which is not what you want.
I'd just like to add that Math.pow(x, 2) can be written more simply (and possibly more accurately and more efficiently) as x * x ... for any variable or constant x.
Look at your executing equation if you know about BODMAS method:
You should do: (1-(2*p))* Math.exp(-p);
I just changed your equation by inserting round brackets around 1-2*p..
I have a double in Java and I want to check if it is NaN.
What is the best way to do this?
Use the static Double.isNaN(double) method, or your Double's .isNaN() method.
// 1. static method
if (Double.isNaN(doubleValue)) {
...
}
// 2. object's method
if (doubleObject.isNaN()) {
...
}
Simply doing:
if (var == Double.NaN) {
...
}
is not sufficient due to how the IEEE standard for NaN and floating point numbers is defined.
Try Double.isNaN():
Returns true if this Double value is a Not-a-Number (NaN), false otherwise.
Note that [double.isNaN()] will not work, because unboxed doubles do not have methods associated with them.
You might want to consider also checking if a value is finite via Double.isFinite(value). Since Java 8 there is a new method in Double class where you can check at once if a value is not NaN and infinity.
/**
* Returns {#code true} if the argument is a finite floating-point
* value; returns {#code false} otherwise (for NaN and infinity
* arguments).
*
* #param d the {#code double} value to be tested
* #return {#code true} if the argument is a finite
* floating-point value, {#code false} otherwise.
* #since 1.8
*/
public static boolean isFinite(double d)
You can check for NaN by using var != var. NaN does not equal NaN.
EDIT: This is probably by far the worst method. It's confusing, terrible for readability, and overall bad practice.
If your value under test is a Double (not a primitive) and might be null (which is obviously not a number too), then you should use the following term:
(value==null || Double.isNaN(value))
Since isNaN() wants a primitive (rather than boxing any primitive double to a Double), passing a null value (which can't be unboxed to a Double) will result in an exception instead of the expected false.
The below code snippet will help evaluate primitive type holding NaN.
double dbl = Double.NaN;
Double.valueOf(dbl).isNaN() ? true : false;
Beginners needs practical examples. so try the following code.
public class Not_a_Number {
public static void main(String[] args) {
String message = "0.0/0.0 is NaN.\nsimilarly Math.sqrt(-1) is NaN.";
String dottedLine = "------------------------------------------------";
Double numerator = -2.0;
Double denominator = -2.0;
while (denominator <= 1) {
Double x = numerator/denominator;
Double y = new Double (x);
boolean z = y.isNaN();
System.out.println("y = " + y);
System.out.println("z = " + z);
if (z == true){
System.out.println(message);
}
else {
System.out.println("Hi, everyone");
}
numerator = numerator + 1;
denominator = denominator +1;
System.out.println(dottedLine);
} // end of while
} // end of main
} // end of class