Creating a log function with a custom base - objective-c

I have a formula and this formula uses a log function with a custom base for example log with a base of b and value of x. In objective-c, I know there are log functions that calculate without a base and base of either 2 or 10.
Is there a function that has the ability to calculate a log function with a custom/variable base? or maybe there is an alternative method of completing this formula.
The basic idea of my formula is this log(1+0.02)(1.26825) (1+0.02 is the base). This should equal 12.000.

Like this:
double logWithBase(double base, double x) {
return log(x) / log(base);
}

You can calculate arbitrary logarithms with logbx = logcx / logcb, where c is one of the more readily available bases such as 10 or e.
For your particular example, loge1.26825 = 0.237637997 and loge1.02 = 0.019802627. That's 12.000 (within the limits of my calculator's accuracy): 0.237637997 / 0.019802627 = 12.000326876.
In fact, 1.0212 is actually 1.268241795 and, if you use that value, you get much closer to 12:
loge1.268241795 = 0.237631528
loge1.02 = 0.019802627
0.237631528 / 0.019802627 = 12.000000197.

Ray is right but here is a Obj-C method modification of it:
-(double) logWithBase:(double)base andNumber:(double)x {
return log(x) / log(base);
}

Related

Iterative solution to compute powers

I am working on developing an efficient iterative code to compute mn. After some thinking and googling I found this code;
public static int power(int n, int m)
// Efficiently calculates m to the power of n iteratively
{
int pow=m, acc=1, count=n;
while(count!=0)
{
if(count%2==1)
acc=acc*pow;
pow=pow*pow;
count=count/2;
}
return acc;
}
This logic makes sense to me except the fact that why are we squaring value of pow towards the end each time. I am familiar with similar recursive approach, but this squaring is not looking very intuitive to me. Can I kindly get some help her? An example with explanation will be really helpful.
The accumulator is being squared each iteration because count (which is the inverse cumulative power) is being halved each iteration.
If the count is odd, the accumulator is multiplied by the number. This algorithm relies on integer arithmetic, which discards the fractional part of a division, effectively further decrementing by 1 when the count is odd.
This is a very tricky solution to understand. I am solving this problem in leetcode and have found the iterative solution. I have spent a whole day to understand this beautiful iterative solution. The main problem is this iterative solution does not work as like its recursive solution.
Let's pick an example to demonstrate. But first I have to re-write your code by replacing some variable name as the name in your given code is very confusing.
// Find m^n
public static int power(int n, int m)
{
int pow=n, result=1, base=m;
while(pow > 0)
{
if(pow%2 == 1) result = result * base;
base = base * base;
pow = pow/2;
}
return result;
}
Let's understand the beauty step by step.
Let say, base = 2 and power = 10.
Calculation
Description
2^10= (2*2)^5 = 4^5
even
We have changed the base to 4 and power to 5. So it is now enough to find 4^5. [base multiplied with itself and power is half
4^5= 4*(4)^4 = 4^5
odd
We separate single 4 which is the base for current iteration. We store the base to result variable. We will now find the value of 4^4 and then multiply with the result variable.
4^4= (4*4)^2 = 16^2
even
We change the base to 16 and power to 2. It is now enough to find 16^2
16^2= (16*16)^1 = 256^1
even
We change the base to 256 and power to 1. It is now enough to find 256^1
256^1 = 256 * 256^0
odd
We separate single 256 which is the base for current iteration. This value comes from evaluation of 4^4.So, we have to multiply it with our previous result variable. And continue evaluating the rest value of 256^0.
256^0
zero
Power 0. So stop the iteration.
So, after translating the process in pseudo code it will be similar to this,
If power is even:
base = base * base
power /= 2
If power is odd:
result = result * base
power -= 1
Now, let have another observation. It is observed that floor(5 / 2) and (5-1) / 2 is same.
So, for odd power, we can directly set power / 2 instead of power -= 1. So, the pseudo code will be like the below,
if power is both odd or even:
base = base * base
power /= 2
If power is odd:
result = result * base
I hope you got the behind the scene.

Blender draw list via script, Add Mesh: Extra Object

I am trying to "visualize" a list of numbers from a .csv file.
I could do that by writing a blender script and thats what I already did.
But I would like to know how the Add Mesh: Extra Object - Math Function could help me (or other functions/addons/anything).
I would like to have a 2D Line (x=+1, y=0, z= value from list) that I would rotate afterwards.
In other words can I convert a list of numbers into a function ?
Sorry if that is a stupid question.
Thanks for the help.
Where The Extra Object - Math Function addon uses minU maxU and stepU as user input values that are used to calculate the value of u before evaluating the function to generate the mesh, you want to let the user input an int value and use it as an index into an array -
AvailZOptions = [1.3, 2.6, 5.2, 10.4]
lineEnd = [xvalue, yvalue, AvailZOptions[OptZUserChoice]]
Another option would be to get the zValue from a function -
def CalcZValue:
if OptZUserChoice = 1:
return 1.3
elif OptZUserChoice = 2:
return 2.6 * cos(x)
lineEnd = [xvalue, yvalue, CalcZValue]

Iteration to find number (from exponential function)

I finally got the formula for the distance from a curve to a point running:
approx = 2 * (b * (Math.Log(a) * (Math.Log(k) * Math.Pow(k, (b * cycleX))) * Math.Pow(a, (Math.Pow(k, (b * cycleX)))) * (Math.Pow(a, (Math.Pow(k, (b * cycleX))))) - points[i].Y) + cycleX - points[i].X);
So, as approx goes closer to 0, the cycleX gives me the right coordinate from which to calculate the distance to the point.
The only issue here is defining a way to modify cycleX. I tried using a series of if's, but with them sometimes approx ends up jumping on to positive numbers (coming from negatives). What should I do to get the right modification to the value of cycleX?
Note: It usually needs to come down to 0.0001 to get something within the range of -1 to 1.
For this kind of problem, it's often useful to know about Newton's method:
Of course, the forumula for that is
Of course, besides the fact that for some functions this quite unstable (I don't expect yours to be, though), implemented purely for your case, it would mean you would need to calculate yet another derivative (of your derivative)! However, I think for your case, you might be able to just approximate the derivative.
You didn't mention the language your implementation would eventually be in, so I'll just use javascript for convenience.
To estimate your derivative, simply choose a deltaX that would be convenient.
So if you have a function
var df = function (cycleX) {
return 2 * (b * (Math.log(a) * (Math.log(k) * Math.pow(k, (b * cycleX))) * Math.pow(a, (Math.pow(k, (b * cycleX)))) * (Math.pow(a, (Math.pow(k, (b * cycleX))))) - Y) + cycleX - X);
};
you can estimate it's derivative via
y = df(cycleX);
y1 = (df(cycleX + deltaX) - y) / deltaX;
And then proceed via.
cycleXnew = cycleX - y / y1;
And then it's just a matter of looping until it converges (or not).
See example jsFiddle: http://jsfiddle.net/jfcox/3wRtj/
Edit: I give no guarantees as to how fast it might converge or even how well an estimated derivative would work with respect to Newton's method. For the parameters I've tried given your function f(x) = a^(k^(bx)), it seems to work well, but I haven't tried much.
Edit II. Of course, the above jsFiddle also assumes only a single solution that we'd need to search for.

Lucene SpellChecker Prefer Permutations or special scoring

I'm using Lucene.NET 3.0.3
How can I modify the scoring of the SpellChecker (or queries in general) using a given function?
Specifically, I want the SpellChecker to score any results that are permutations of the searched word higher than the the rest of the suggestions, but I don't know where this should be done.
I would also accept an answer explaining how to do this with a normal query. I have the function, but I don't know if it would be better to make it a query or a filter or something else.
I think the best way to go about this would be to use a customized Comparator in the SpellChecker object.
Check out the source code of the default comparator here:
http://grepcode.com/file/repo1.maven.org/maven2/org.apache.lucene/lucene-spellchecker/3.6.0/org/apache/lucene/search/spell/SuggestWordScoreComparator.java?av=f
Pretty simple stuff, should be easy to extend if you already have the algorithm you want to use to compare the two Strings.
Then you can use set it up to use your comparator with SpellChecker.SetComparator
I think I mentioned the possiblity of using a Filter for this in a previous question to you, but I don't think that's really the right way to go, looking at it a bit more.
EDIT---
Indeed, No Comparator is available in 3.0.3, So I believe you'll need to access the scoring through the a StringDistance object. The Comparator would be nicer, since the scoring has already been applied and is passed into it to do what you please with it. Extending a StringDistance may be a bit less concrete since you will have to apply your rules as a part of the score.
You'll probably want to extend LevensteinDistance (source code), which is the default StringDistance implementation, but of course, feel free to try JaroWinklerDistance as well. Not really that familiar with the algorithm.
Primarily, you'll want to override getDistance and apply your scoring rules there, after getting a baseline distance from the standard (parent) implementation's getDistance call.
I would probably implement something like (assuming you ahve a helper method boolean isPermutation(String, String):
class CustomDistance() extends LevensteinDistance{
float getDistance(String target, String other) {
float distance = super.getDistance();
if (isPermutation(target, other)) {
distance = distance + (1 - distance) / 2;
}
return distance;
}
}
To calculate a score half again closer to 1 for a result that is a permuation (that is, if the default algorithm gave distance = .6, this would return distance = .8, etc.). Distances returned must be between 0 and 1. My example is just one idea of a possible scoring for it, but you will likely need to tune your algorithm somewhat. I'd be cautious about simply returning 1.0 for all permutations, since that would be certain to prefer 'isews' over 'weis' when looking with 'weiss', and it would also lose the ability to sort the closeness of different permutations ('isews' and 'wiess' would be equal matches to 'weiss' in that case).
Once you have your Custom StringDistance it can be passed to SpellChecker either through the Constructor, or with SpellChecker.setStringDistance
From femtoRgon's advice, here's what I ended up doing:
public class PermutationDistance: SpellChecker.Net.Search.Spell.StringDistance
{
public PermutationDistance()
{
}
public float GetDistance(string target, string other)
{
LevenshteinDistance l = new LevenshteinDistance();
float distance = l.GetDistance(target, other);
distance = distance + ((1 - distance) * PermutationScore(target, other));
return distance;
}
public bool IsPermutation(string a, string b)
{
char[] ac = a.ToLower().ToCharArray();
char[] bc = b.ToLower().ToCharArray();
Array.Sort(ac);
Array.Sort(bc);
a = new string(ac);
b = new string(bc);
return a == b;
}
public float PermutationScore(string a, string b)
{
char[] ac = a.ToLower().ToCharArray();
char[] bc = b.ToLower().ToCharArray();
Array.Sort(ac);
Array.Sort(bc);
a = new string(ac);
b = new string(bc);
LevenshteinDistance l = new LevenshteinDistance();
return l.GetDistance(a, b);
}
}
Then:
_spellChecker.setStringDistance(new PermutationDistance());
List<string> suggestions = _spellChecker.SuggestSimilar(word, 10).ToList();

Calculate variance with VB.NET lambda expression

I am trying to convert the following code for the variance calculation
public static double Variance(this IEnumerable<double> source)
{
double avg = source.Average();
double d = source.Aggregate(0.0,
(total, next) => total += Math.Pow(next - avg, 2));
return d / (source.Count() - 1);
}
described on CodeProject into corresponded VB.NET lambda expression syntax, but I am stuck in the conversion of Aggregate function.
How can I implement that code in VB.NET?
The following will only work in VB 10. Prior versions didn’t support multi-line lambdas.
Dim d = source.Aggregate(0.0,
Function(total, next)
total += (next - avg) ^ 2
Return total
End Function)
Function(foo) bar corresponds to the single-statement lambda (foo) => bar in C# but you need the multi-line lambda here which only exists since VB 10.
However, I’m wary of the original code. Modifying total seems like an error, since no Aggregate overload passes its arguments by reference. So I’m suggesting that the original code is wrong (even though it may actually compile), and that the correct solution (in VB) would look like this:
Dim d = source.Aggregate(0.0, _
Function(total, next) total + (next - avg) ^ 2)
Furthermore, this doesn’t require any multi-line lambdas, and thus also works on older versions of VB.