isolate real number in complex number in java - java

There is a formula i need to use for my app : here
the part Sqrt(5-25) , can be positive or negative , and of course when negative we got a imaginary part that java cant handle.
i've searched around to find a complex class to handle that , but found only basic operation (+-*/).
how can i solve this in java knowing i only need to get the real part ?(imaginary have no importance)
i precise that i develop on android platform
(i post on stack because it's concerning application in java , but if its belong to math.se , tell me)

You can simply compute verything before:
plot 25-20+((2Pi0.3²)/(Pi10²)Sqrt[2*980(1+(Pi10²)/(Pi10²))]t)² from 0 to 38
or
plot 25-20+((2*0.3²)/(10²)Sqrt[2*980(1+1)]t)² from 0 to 38
or
25 - 20 + 4 * 0.0000081 * 3920*t^2 from 0 to 38 (I have some factor wrong, but you get the idea)
just apply basic math to the constants and remove the middle (imaginary part) after applying the 2nd binomic formula.
There is nothing to do with complex numbers.

Taking the Square root of a general complex number can be done with the basic arithmetic operations on real numbers (plus taking square root of reals): http://www.mathpropress.com/stan/bibliography/complexSquareRoot.pdf (one technique is to utilise De Moivre's theorem: Any complex number a + bi can be written as r(cos θ + i sin θ) where
r = sqrt(a^2 + b^2), cos θ = a/r, sin θ = b/r
Update: the formula r(cos θ + i sin θ) is originaly due to Euler, whereas De Moivre's theorem is
(a + ib)ⁿ = rⁿ(cos nθ + i sin nθ)

You are confused about the math. Square root of -25 is square root of 25*(-1) and that is square root of 25 * square root of -1 and that is 5i. Real part of that number is 0.
If you want the 5, just check for the sign of the number to be "rooted" and change it if it is negative.

It's not right to say that "Java can't handle it". No language that returns a double from a square root can handle it, but if you have a Complex class it's not an issue. Python has one built in; it's easy to write one in Java.

The square root of an integer is going to be an integer or a complex number whose real part is zero. The real part of the square root of a negative integer is zero. Always.
So ...
public double realPartOfSquareRoot(int i) {
return (i > 0) Math.sqrt(i) : 0;
}
But how I solve this? If I replace the squareroot by 0, I don't get a good result. Do I suppose the imaginary part do something on the real with the rest of the formula.
I expect that's so! (The idea of discarding the imaginary part didn't make much sense to me ... but I assumed you had a sound reason to do this.)
The real answer is to find a Java library that will do complex arithmetic. I've never needed to use it, but the first one to examine should be the Apache Commons Maths library.

Related

How derive a formula for (measurement) unit conversion of arbitrary compound units?

I'm developing a calculator application which also does allow to convert between units. For this I want to provide the feature to not only convert between arbitrary (measurement) units, but also between arbitrary compound units, like km/h to m/s. First, let me start with the structure I have so that you understand setup.
I have all units and conversions specified in configuration files to give the user the possibility to extend the system with more units. The overall layout of the files (wrapped into one here) looks like this:
# This is a comment.
# Unit declaration
# Name Dimension Aliases
meter 1 Metre, metre, m
foot 1 ft, feet
second 1 s,sec
hour 1 h
# Prefix
# Name Alias Base Exponent
centi c 10 -2
kilo k 10 3
# Conversion
foot 30.48cm
hour 3600sec
These are all then wrapped into types/objects for processing. Finding "hops" between arbitrary units is fully implemented, that means that the system can already find a path to convert between units which do not have a direct conversion assigned. For example, I only could specify an hour to be 60 minutes, and a minute as 60 seconds and the system could convert 1 hour into 3600 seconds. That is all working. Also fully working is the prefix support.
My problem starts with unit conversions which are not consisting of a simple factor, for example temperature conversions:
celsius (x * (9/5) + 32)°F
fahrenheit ((x - 32) * (5/9))°C
As you can see, I already have a system in place which allows to place arbitrary formulas as conversion with x as the number that is being converted. Now, the main problem are compound units, for example when I want to convert km/h to ft/s. My current approach is to as follows (warning, not for the faint of heart):
Split the compound unit into its components: km and h, ft and s
Match the units against each other: km and ft,hands`
Derive a formula from this point:
Convert all prefixed units to their bases: km to 1000m
Get the conversion factor between units and place that in the formula.
That yields ((1 * 1000) * 3.28) / (3600) as a derivation formula, and a factor of 0.911... roughly, which I then use to convert the given value to ft/s. So far, so well.
Now, when we think back on the temperature conversions, this whole approach falls apart because I'm using 1 as value in the formula. Assuming I want to convert C/s to F/h I'm currently deriving the formula (1 * (9/5) + 32) / (0.0002777) and using the resulting factor for the conversion, which is plain out wrong.
My second approach was to insert the value (assume 9) at each unit conversion, which gives me (9 * (9/5) + 32) / (9 * 0.0002777), which also is not the right thing to do. I mean, the case of such temperature conversions are much more complicated, too. So there is still a certain knowledge gap on my end.
I'm quite at a loss here and have a hard time locating resources or solutions to this problem. Can somebody shed some light on how to do this properly?
I'm not sure how exactly to solve your problem but here is my idea what is wrong.
In general your approach seems to work fine. The problem is that temperature is probably a special case. What actually would F/h or C/s represent? I don't think there is such concept in physics. What you have probably thought about is change of temperature in time, which would be (delta C) / h. Your formula for converting delta C to delta F would look like this I believe: (x1 * (9/5) + 32) - (x2 * (9/5) + 32) = (x1-x2)*(9/5). Then you can use that in the formula for converting complex units.
I can't say on top of my head if there are more cases like this one, you will have to check other units with weird convertion ratios as well.
I hope this is helpful enough and will guide you into solving your problem.

Minimize complex linear multivariable function in java

I need to minimize a complex linear multivariable function under some constraints.
Let x be an array of complex numbers of length L.
a[0], a[1], ..., a[L-1] are complex coefficients and
F is the complex function F(x)= x[0]*a[0] + x[1]*a[1] + ... + x[L-1]*a[L-1] that has to be minimized.
b[0], b[1], ..., b[L-1] are complex coefficients and there is a constraint
1 = complexConjuate(x[0])*x[0] + complexConjuate(x[1])*x[1] + ... + complexConjuate(x[L-1])*x[L-1] that has to be fulfilled.
I already had a detailed look at http://math.nist.gov/javanumerics/ and went through many documentations. But I couldn't find a library which does minimization for complex functions.
You want to minimize a differentiable real-valued function f on a smooth hypersurface S. If such a minimum exists - in the situation after the edit it is guaranteed to exist because the hypersurface is compact - it occurs at a critical point of the restriction f|S of f to S.
The critical points of a differentiable function f defined in the ambient space restricted to a manifold M are those points where the gradient of f is orthogonal to the tangent space T(M) to the manifold. For the general case, read up on Lagrange multipliers.
In the case where the manifold is a hypersurface (it has real codimension 1) defined (locally) by an equation g(x) = 0 with a smooth function g, that is particularly easy to detect, the critical points of f|S are the points x on S where grad(f)|x is collinear with grad(g)|x.
Now the problem is actually a real (as in concerns the real numbers) problem and not a complex (as in concerning complex numbers) one.
Stripping off the unnecessary imaginary parts, we have
the hypersurface S, which conveniently is the unit sphere, globally defined by (x|x) = 1 where (a|b) denotes the scalar product a_1*b_1 + ... + a_k*b_k, the gradient of g at x is just 2*x
a real linear function L(x) = (c|x) = c_1*x_1 + ... + c_k*x_k, the gradient of L is c independent of x
So there are two critical points of L on the sphere (unless c = 0 in which case L is constant), the points where the line through the origin and c intersects the sphere, c/|c| and -c/|c|.
Obviously L(c/|c|) = 1/|c|*(c|c) = |c| and L(-c/|c|) = -1/|c|*(c|c) = -|c|, so the minimum occurs at -c/|c| and the value there is -|c|.
Each complex variable x can be considered as two real variables, representing the real and imaginary part, respectively, of x.
My recommendation is that you reformulate your objective function and constraint using the real and imaginary parts of each variable or coefficient as independent components.
According to the comments, you only intend to optimize the real part of the objective function, so you can end up with a single objective function subject to optimization.
The constraint can be split into two, where the "real" constraint should equal 1 and the "imaginary" constraint should equal 0.
After having reformulated the optimization problem this way, you should be able to apply any optimization algorithm that is applicable to the reformulated problem. For example, there is a decent set of optimizers in the Apache Commons Math library, and the SuanShu library also contains some optimization algorithms.

Need an algorithm for square root that provides a "remainder"

I'm writing a calculator without using decimals (supports only Rational numbers), but I'd like to be able to do a version of square root.
When a square root function is pressed for (say) the number 12, I'd like to just simplify/"reduce" the square root and return 2*sqrt(3)--by it into (2*2) * 3 and extracting the sqrt(2*2) as 2.
I'm using biginteger which has a very nice gcd() method and a pow() method that is restricted to positive parameters (which makes sense unless you are trying to do exactly what I'm trying to do.
I could come up with a few iterative ways to do this but they may take a while with numbers in the hundreds-of-digits range.
I'm hoping there is some cute, simple, non-iterative trick I haven't been exposed to.
Just to clarify: I have the intent to add imaginary numbers so I'm planning on results like this:
17 + 4i √3
-----------
9
Without long streams of decimals.
What you're asking, in essence, is to find all repeated prime factors. Since you're dealing with numbers in the hundreds-of-digits range, I'm going to venture a guess here that there are no good ways to do this in general. Otherwise public key cryptography will all of a sudden be on somewhat shaky ground.
There are a number of methods of computing the square root. With those, you can express the result as an integer plus a remainder less than 1.
Maybe try finding the highest perfect square that is less than your number. That will give you part of the equation, then you would only need to handle the remainder part which is the difference between your number and the perfect square you found. This would degrade as numbers get large as well, but perhaps not as fast.

How to find function range?

I have an arbitrary function or inequality (consisting of a number of trigonometrical, logarithmical, exponential, and arithmetic terms) that takes several arguments and I want to get its range knowing the domains of all the arguments. Are there any Java libraries that can help to solve a problem? What are the best practices to do that? Am I right that for an arbitrary function the only thing can be done is a brute-force approximation? Also, I'm interested in functions that can build intersections and complements for given domains.
Upd. The functions are entered by the user so the complexity cannot be predicted. However, if the library will treat at least simple cases (1-2 variables, 1-2 terms) it will be OK. I suggest the functions will mostly define the intervals and contain at most 2 independent variables. For instance, definitions like
y > (x+3), x ∈ [-7;8]
y <= 2x, x ∈ [-∞; ∞]
y = x, x ∈ {1,2,3}
will be treated in 99% of cases and covering them will be enough for now.
Well, maybe it's faster to write a simple brute-force for treating such cases. Probably it will be satisfactory for my case but if there are better options I would like to learn them.
Notational remark: I assume you want to find the range of the function, i.e. the set of values that the function can take.
I think this problem is not simple. I don't think that "brute force" is a solution at all, what does "brute force" even mean when we have continuous intervals (i.e infinitely many points!).
However, there might be some special cases where this is actually possible. For example, when you take a sin(F(x)) function, you know that its range is [-1,1], regardless of the inner function F(x) or when you take Exp(x) you know the range is (0,+inf).
You could try constructing a syntax tree with information about the ranges associated to each node. Then you could try going bottom-up through the tree to try to compute the information about the actual intervals in which the function values lie.
For example, for the function Sin(x)+Exp(x) and x in (-inf, +inf) you would get a tree
+ range: [left range] union [right range]
/ \
sin exp range [-1, 1] , range: (0,+inf)
| |
x x
so here the result would be [-1, 1] union (0, +inf) = [-1, +inf).
Of course there are many problems with this approach, for example the operation on ranges for + is not always union. Say you have two functions F(x) = Sin(x) and G(x) = 1-Sin(x). Both have ranges [-1,1], but their sum collapses to {1}. You need to detect and take care of such behaviour, otherwise you will get only an upper bound on the possible range (So sort of codomain).
If you provide more examples, maybe someone can propose a better solution, I guess a lot depends on the details of the functions.
#High Performance Mark: I had a look at JAS and it seems that its main purpose is to deal with multivariate polynomial rings, but the question mentioned trigonometric, logarithmic and other transcendental functions so pure polynomial arithmetic will not be sufficient.
Here's another approach and depending on how crazy your function can be (see EDIT) it might give you the universal solution to your problem.
Compose the final expression, which might be rather complex.
After that use numerical methods to find minimum and maximum of the function - this should give you the resulting range.
EDIT: Only in the case that your final expression is not continuous the above would not work and you would have to divide into continuous sections for each you would have to find min and max. At the end you would have to union those.
I would have thought that this is a natural problem to tackle with a Computer Algebra System. I googled around and JAS seems to be the most-cited Java CAS.
If I had to confine myelf to numeric approaches, then I'd probably tackle it with some variety of interval computations. So: the codomain of sin is [-1,1], the codomain of exp is (0,+Inf), and the codomain of exp(sin(expression)) is ...
over to you, this is where I'd reach for Mathematica (which is callable from Java).

Scale numbers to be <= 255?

I have cells for whom the numeric value can be anything between 0 and Integer.MAX_VALUE. I would like to color code these cells correspondingly.
If the value = 0, then r = 0. If the value is Integer.MAX_VALUE, then r = 255. But what about the values in between?
I'm thinking I need a function whose limit as x => Integer.MAX_VALUE is 255. What is this function? Or is there a better way to do this?
I could just do (value / (Integer.MAX_VALUE / 255)) but that will cause many low values to be zero. So perhaps I should do it with a log function.
Most of my values will be in the range [0, 10,000]. So I want to highlight the differences there.
The "fairest" linear scaling is actually done like this:
floor(256 * value / (Integer.MAX_VALUE + 1))
Note that this is just pseudocode and assumes floating-point calculations.
If we assume that Integer.MAX_VALUE + 1 is 2^31, and that / will give us integer division, then it simplifies to
value / 8388608
Why other answers are wrong
Some answers (as well as the question itself) suggsted a variation of (255 * value / Integer.MAX_VALUE). Presumably this has to be converted to an integer, either using round() or floor().
If using floor(), the only value that produces 255 is Integer.MAX_VALUE itself. This distribution is uneven.
If using round(), 0 and 255 will each get hit half as many times as 1-254. Also uneven.
Using the scaling method I mention above, no such problem occurs.
Non-linear methods
If you want to use logs, try this:
255 * log(value + 1) / log(Integer.MAX_VALUE + 1)
You could also just take the square root of the value (this wouldn't go all the way to 255, but you could scale it up if you wanted to).
I figured a log fit would be good for this, but looking at the results, I'm not so sure.
However, Wolfram|Alpha is great for experimenting with this sort of thing:
I started with that, and ended up with:
r(x) = floor(((11.5553 * log(14.4266 * (x + 1.0))) - 30.8419) / 0.9687)
Interestingly, it turns out that this gives nearly identical results to Artelius's answer of:
r(x) = floor(255 * log(x + 1) / log(2^31 + 1)
IMHO, you'd be best served with a split function for 0-10000 and 10000-2^31.
For a linear mapping of the range 0-2^32 to 0-255, just take the high-order byte. Here is how that would look using binary & and bit-shifting:
r = value & 0xff000000 >> 24
Using mod 256 will certainly return a value 0-255, but you wont be able to draw any grouping sense from the results - 1, 257, 513, 1025 will all map to the scaled value 1, even though they are far from each other.
If you want to be more discriminating among low values, and merge many more large values together, then a log expression will work:
r = log(value)/log(pow(2,32))*256
EDIT: Yikes, my high school algebra teacher Mrs. Buckenmeyer would faint! log(pow(2,32)) is the same as 32*log(2), and much cheaper to evaluate. And now we can also factor this better, since 256/32 is a nice even 8:
r = 8 * log(value)/log(2)
log(value)/log(2) is actually log-base-2 of value, which log does for us very neatly:
r = 8 * log(value,2)
There, Mrs. Buckenmeyer - your efforts weren't entirely wasted!
In general (since it's not clear to me if this is a Java or Language-Agnostic question) you would divide the value you have by Integer.MAX_VALUE, multiply by 255 and convert to an integer.
This works! r= value /8421504;
8421504 is actually the 'magic' number, which equals MAX_VALUE/255. Thus, MAX_VALUE/8421504 = 255 (and some change, but small enough integer math will get rid of it.
if you want one that doesn't have magic numbers in it, this should work (and of equal performance, since any good compiler will replace it with the actual value:
r= value/ (Integer.MAX_VALUE/255);
The nice part is, this will not require any floating-point values.
The value you're looking for is: r = 255 * (value / Integer.MAX_VALUE). So you'd have to turn this into a double, then cast back to an int.
Note that if you want brighter and brighter, that luminosity is not linear so a straight mapping from value to color will not give a good result.
The Color class has a method to make a brighter color. Have a look at that.
The linear implementation is discussed in most of these answers, and Artelius' answer seems to be the best. But the best formula would depend on what you are trying to achieve and the distribution of your values. Without knowing that it is difficult to give an ideal answer.
But just to illustrate, any of these might be the best for you:
Linear distribution, each mapping onto a range which is 1/266th of the overall range.
Logarithmic distribution (skewed towards low values) which will highlight the differences in the lower magnitudes and diminish differences in the higher magnitudes
Reverse logarithmic distribution (skewed towards high values) which will highlight differences in the higher magnitudes and diminish differences in the lower magnitudes.
Normal distribution of incidence of colours, where each colour appears the same number of times as every other colour.
Again, you need to determine what you are trying to achieve & what the data will be used for. If you have been tasked to build this then I would strongly recommend you get this clarified to ensure that it is as useful as possible - and to avoid having to redevelop it later on.
Ask yourself the question, "What value should map to 128?"
If the answer is about a billion (I doubt that it is) then use linear.
If the answer is in the range of 10-100 thousand, then consider square root or log.
Another answer suggested this (I can't comment or vote yet). I agree.
r = log(value)/log(pow(2,32))*256
Here are a bunch of algorithms for scaling, normalizing, ranking, etc. numbers by using Extension Methods in C#, although you can adapt them to other languages:
http://www.redowlconsulting.com/Blog/post/2011/07/28/StatisticalTricksForLists.aspx
There are explanations and graphics that explain when you might want to use one method or another.
The best answer really depends on the behavior you want.
If you want each cell just to generally have a color different than the neighbor, go with what akf said in the second paragraph and use a modulo (x % 256).
If you want the color to have some bearing on the actual value (like "blue means smaller values" all the way to "red means huge values"), you would have to post something about your expected distribution of values. Since you worry about many low values being zero I might guess that you have lots of them, but that would only be a guess.
In this second scenario, you really want to distribute your likely responses into 256 "percentiles" and assign a color to each one (where an equal number of likely responses fall into each percentile).
If you are complaining that the low numbers are becoming zero, then you might want to normalize the values to 255 rather than the entire range of the values.
The formula would become:
currentValue / (max value of the set)
I could just do (value / (Integer.MAX_VALUE / 255)) but that will cause many low values to be zero.
One approach you could take is to use the modulo operator (r = value%256;). Although this wouldn't ensure that Integer.MAX_VALUE turns out as 255, it would guarantee a number between 0 and 255. It would also allow for low numbers to be distributed across the 0-255 range.
EDIT:
Funnily, as I test this, Integer.MAX_VALUE % 256 does result in 255 (I had originally mistakenly tested against %255, which yielded the wrong results). This seems like a pretty straight forward solution.

Categories

Resources