Delegates help java to c# - java

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?

Related

Java: Finding the value in an array list that is closest to a particular negative number

My question is how I can write a method that takes an ArrayList of Doubles as a parameter and returning the Double in the array list that is closest to -3.75.
I got the code down for the positive number 3.42, but I'm stuck as to modifying it to suit -3.75
public static double question3(ArrayList<Double> input) {
double myNum = 3.42.;
double dist = Double.POSITIVE_INFINITY;
double closest = 0.0;
for (Double s : input) {
if (Math.abs(Math.abs(s) - myNum) < dist) {
dist = Math.abs(Math.abs(s) - myNum);
closest = s;
}
}
System.out.println(closest);
return closest;
}
Any help? Or better way to go about performing this task?
If it's not your explicit goal to reinvent the wheel, you can use stream's min with a custom comparator:
public double findClosestTo(ArrayList<Double> arr, double value) {
return arr.stream().min(
Comparator.<Double>comparingDouble(x -> Math.abs(x - value))
).get();
}
The get part (that comes from Optional) will throw an error if the array is empty.
Here, you got the absolute value of s:
if (Math.abs(Math.abs(s) - myNum) < dist) {
^^^^^^^^^^^
This means that every negative number in the array will be treated as if it were a positive number. This is why your method cannot find the correct closest number to -3.75.
Just remove the abs call:
if (Math.abs(s - myNum) < dist) {
Alternatively, use the Stream API like this:
return input.stream()
// compares the value of Math.abs(x - myNum), where x is each element of input
.min(Comparator.comparingDouble(x -> Math.abs(x - myNum)))
// returns positive infinity if there is nothing in "input"
.orElse(Double.POSITIVE_INFINITY);
But since this looks like homework, I doubt a Stream API approach will be accepted...

Division by zero in Java with "IsInfinite" and "POSITIVE_INFINITY" or "NEGATIVE_INFINITY"

I'm a completely noob in java and I have to make this:
Write a program that asks for the introduction of the dividend and the divisor (both real numbers) and show the result of the division in the output. If the result is infinite, the screen must show the text “The result is infinite”. Use the IsInfinite method for the corresponding wrapper class (or the comparison with the constants POSITIVE_INFINITY and NEGATIVE_INFINITY for the corresponding wrapper class).
The main problem is that I don't know how to use the IsInfinite method or the constants method (others methods worked). I have been searching on internet but I didn't find a solution.
Can you help me please?
EDIT: I did this but I don't know if it is what EXACTLY I have to do.
import java.util.Scanner;
public class Exercise {
public static void main(String[] args) {
Scanner key=new Scanner(System.in);
System.out.println("Dividend:");
double dividend=key.nextDouble();
System.out.println("Divisor:");
double divisor=key.nextDouble();
double x = dividend/divisor;
if (x == Double.POSITIVE_INFINITY | x == Double.NEGATIVE_INFINITY) {
System.out.println("The result is infinite");
} else {
System.out.println("The quotient is: " + dividend/divisor);
}
}
}
The code you have given worked for me.
However, you might want to change these lines:
double x = dividend/divisor;
if (x == Double.POSITIVE_INFINITY | x == Double.NEGATIVE_INFINITY) {
to this:
Double x = dividend / divisor;
if (x.isInfinite()) {
Notice the capital D in Double. This is the wrapper class of the primitive double. This class contains the isInfinite method.

Java- Notation for /variable/

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.

Java double and working with really small values

I have to store the product of several probabilty values that are really low (for example, 1E-80). Using the primitive java double would result in zero because of the underflow. I don't want the value to go to zero because later on there will be a larger number (for example, 1E100) that will bring the values within the range that the double can handle.
So, I created a different class (MyDouble) myself that works on saving the base part and the exponent parts. When doing calculations, for example multiplication, I multiply the base parts, and add the exponents.
The program is fast with the primitive double type. However, when I use my own class (MyDouble) the program is really slow. I think this is because of the new objects that I have to create each time to create simple operations and the garbage collector has to do a lot of work when the objects are no longer needed.
My question is, is there a better way you think I can solve this problem? If not, is there a way so that I can speedup the program with my own class (MyDouble)?
[Note: taking the log and later taking the exponent does not solve my problem]
MyDouble class:
public class MyDouble {
public MyDouble(double base, int power){
this.base = base;
this.power = power;
}
public static MyDouble multiply(double... values) {
MyDouble returnMyDouble = new MyDouble(0);
double prodBase = 1;
int prodPower = 0;
for( double val : values) {
MyDouble ad = new MyDouble(val);
prodBase *= ad.base;
prodPower += ad.power;
}
String newBaseString = "" + prodBase;
String[] splitted = newBaseString.split("E");
double newBase = 0; int newPower = 0;
if(splitted.length == 2) {
newBase = Double.parseDouble(splitted[0]);
newPower = Integer.parseInt(splitted[1]);
} else {
newBase = Double.parseDouble(splitted[0]);
newPower = 0;
}
returnMyDouble.base = newBase;
returnMyDouble.power = newPower + prodPower;
return returnMyDouble;
}
}
The way this is solved is to work in log space---it trivialises the problem. When you say it doesn't work, can you give specific details of why? Probability underflow is a common issue in probabilistic models, and I don't think I've ever known it solved any other way.
Recall that log(a*b) is just log(a) + log(b). Similarly log(a/b) is log(a) - log(b). I assume since you're working with probabilities its multiplication and division that are causing the underflow issues; the drawback of log space is that you need to use special routines to calculate log(a+b), which I can direct you to if this is your issue.
So the simple answer is, work in log space, and re-exponentiate at the end to get a human-readable number.
You trying to parse strings each time you doing multiply. Why don't you calculate all values into some structure like real and exponential part as pre-calculation step and then create algorithms for multiplication, adding, subdivision, power and other.
Also you could add flag for big/small numbers. I think you will not use both 1e100 and 1e-100 in one calculation (so you could simplify some calculations) and you could improve calculation time for different pairs (large, large), (small, small), (large, small).
You can use
BigDecimal bd = BigDecimal.ONE.scaleByPowerOfTen(-309)
.multiply(BigDecimal.ONE.scaleByPowerOfTen(-300))
.multiply(BigDecimal.ONE.scaleByPowerOfTen(300));
System.out.println(bd);
prints
1E-309
Or if you use a log10 scale
double d = -309 + -300 + 300;
System.out.println("1E"+d);
prints
1E-309.0
Slowness might be because of the intermediate string objects which are created in split and string concats.
Try this:
/**
* value = base * 10 ^ power.
*/
public class MyDouble {
// Threshold values to determine whether given double is too small or not.
private static final double SMALL_EPSILON = 1e-8;
private static final double SMALL_EPSILON_MULTIPLIER = 1e8;
private static final int SMALL_EPSILON_POWER = 8;
private double myBase;
private int myPower;
public MyDouble(double base, int power){
myBase = base;
myPower = power;
}
public MyDouble(double base)
{
myBase = base;
myPower = 0;
adjustPower();
}
/**
* If base value is too small, increase the base by multiplying with some number and
* decrease the power accordingly.
* <p> E.g 0.000 000 000 001 * 10^1 => 0.0001 * 10^8
*/
private void adjustPower()
{
// Increase the base & decrease the power
// if given double value is less than threshold.
if (myBase < SMALL_EPSILON) {
myBase = myBase * SMALL_EPSILON_MULTIPLIER;
myPower -= SMALL_EPSILON_POWER;
}
}
/**
* This method multiplies given double and updates this object.
*/
public void multiply(MyDouble d)
{
myBase *= d.myBase;
myPower += d.myPower;
adjustPower();
}
/**
* This method multiplies given primitive double value with this object and update the
* base and power.
*/
public void multiply(double d)
{
multiply(new MyDouble(d));
}
#Override
public String toString()
{
return "Base:" + myBase + ", Power=" + myPower;
}
/**
* This method multiplies given double values and returns MyDouble object.
* It make sure that too small double values do not zero out the multiplication result.
*/
public static MyDouble multiply(double...values)
{
MyDouble result = new MyDouble(1);
for (int i=0; i<values.length; i++) {
result.multiply(values[i]);
}
return result;
}
public static void main(String[] args) {
MyDouble r = MyDouble.multiply(1e-80, 1e100);
System.out.println(r);
}
}
If this is still slow for your purpose, you can modify multiply() method to directly operate on primitive double instead of creating a MyDouble object.
I'm sure this will be a good deal slower than a double, but probably a large contributing factor would be the String manipulation. Could you get rid of that and calculate the power through arithmetic instead? Even recursive or iterative arithmetic might be faster than converting to String to grab bits of the number.
In a performance heavy application, you want to find a way to store basic information in primitives. In this case, perhaps you can split the bytes of a long or other variable in so that a fixed portion is the base.
Then, you can create custom methods the multiply long or Long as if they were a double. You grab the bits representing the base and exp, and truncate accordingly.
In some sense, you're re-inventing the wheel here, since you want byte code that efficiently performs the operation you're looking for.
edit:
If you want to stick with two variables, you can modify your code to simply take an array, which will be much lighter than objects. Additionally, you need to remove calls to any string parsing functions. Those are extremely slow.

How do you test to see if a double is equal to NaN?

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

Categories

Resources