开发者

math function "Log ()"

Is there a way to implement the math function Log() into an equation with an iphone app? im working on right now that without the log function requires about 400 + if and else if statements. I have already wrote out these if and else if statements. half of them work and the other half keeps returning 0.00 . after HOURS of trying to find the problem and compare it to the part that does work i can still not figure it out. i know i can do simple math (add, subtract, divide, mulitply, etc), but i havnt found anything searching forums, google, etc that tells me how to add a Log function. if i could do this i can cut my code down from like 500 lines to about 40 tops. can anyone help me with this or at least point me in the right direction as开发者_开发问答 to where i can find a thread or tutorial on this?


I already fixed Shaun's example code posted in his answer, but just to be perfectly clear, there were two issues at work:

  • First, he wasn't including <math.h> and using log from the system math library.
  • Second, he omitted the multiplication operator in the expression .19077f(logf(abNeckFactor)); we often write mathematics this way, but it is not syntactically valid C (or Obj-C) code.

Shaun, I would advise you to spend some more time reading up on what's available in C and Objective-C; an enormous amount of functionality is present in the language, and a few hours spent learning about what's already done for you will spend you many, many hours of searching for things in the future.

Note also that the log function is the base-e logarithm. Many people in technical fields outside of mathematics and computing use log to refer instead to the base-10 logarithm; if that's what you need, you will want to call log10( ) -- or log10f( ) -- instead.


#import <math.h>

// ...

double someLog = log(someDouble);

(Note: I used double/log here, but you might consider using float/logf if speed is an issue as they could be faster on the iPhone (IIRC).)


I know you've already got the answer to your question, but here's way of not having to write tons of if, else if, else if, .... else, for future reference.

Store the answers in an array. For instance you could define an array of arrays that looks like this: [(min, max, value),(min, max, value),...]. Then loop through the array.

arr = {{min, max, value}, {min, max, value}, ...}
for i in range(0, arr.length) 
  if(arr[i][min_i] < x && x < arr[i][max_i]) {return arr[val_i]}

There is probably a way figuring how to map the x to a index of an array like x/(max-min) so that log(x) would be arr[x/(max-min)]. But my point is, it is alot cleaner to have an array or dictionary and search through it than having a bunch of if, else if, else if, ... statements.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜