NSInteger cannot be used twice in same multiplication [closed] - ios

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I am stumped! I am using NSinteger but as all my inputs are integers and the results are therefore integers I can't see the problem that people doing division are having due to rounding.
I've looked in the developer guide for NSInteger and cannot find a warning.
And my searching of this site and google hasn't yielded results.
As I state at the end I can work around it, but I feel there is something simple I am missing.
All the variables are direct, no pointers yet in the first for loop, intergerOfInterest is 0, 1, 6, 7, 4, 5, 10, 11 which is very random, I have tried swapping integerValueA^2 for the calculation but with no effect. The second for loop however gives the correct answers, 6,12,20,30,2,56,72,90
for (loopCount = 0; loopCount < 8; loopCount++){
integerValueA = loopCount + 2;
integerValueB = integerValueA + 1;
intergerOfInterest = (integerValueA) * (integerValueA);
}
for (loopCount = 0; loopCount < 8; loopCount++){
integerValueA = loopCount + 2;
integerValueB = integerValueA + 1;
intergerOfInterest = (integerValueA) * (integerValueB);
}
There are several loops in the structure and the common factor between the correct number and the incorrect number is if the NSInteger is used more than once in a calculation. I figure this can't be right so does anyone have an idea how I am getting this wrong. Note: if I add an extra variable to store the second instance of the number (so in the first loop I use "(integerValueA) * (integerValueB - 1 )" it works fine.
Note: Edited to use naming conventions.

It sounds from the discussion in the comments that your original code looked something like this:
for(int i = 0; i < 8; i++) {
nVal = i ^ 2; // Supposed to be equivalent to nVal = i * i;
// Do something with nVal
}
The ^ operator in C is actually the bit-wise XOR operator, not the exponent operator. The above code takes i, flips bit 1, and assigns the result to nVal.
You want to use either of the following:
// Option 1
for(int i = 0; i < 8; i++) {
nVal = i * i;
// Do something with nVal
}
// Option 2
for(int i = 0; i < 8; i++) {
nVal = pow(i, 2);
// Do something with nVal
}

Is it possible you have a spelling error on your variable InteRgerOfInterest instead of IntEgerOfInterest ?
GH

Related

Autodiff for Jacobian derivative with respect to individual joint angles

I am trying to compute $\partial{J}{q_i}$ in drake C++ for manipulator and as per my search, the best approach seems to be using autodiff function. I was not able to fully understand autodiff approach from the resources that I found, so I apologize if my approach is not clear enough. I have used my understanding from some already asked questions mentioned on the forum regarding auto diff as well as https://drake.mit.edu/doxygen_cxx/classdrake_1_1multibody_1_1_multibody_plant.html as reference.
As I want to calculate $\partial{J}{q_i}$, the return type will be a tensor i.e. 3 * 7 * 7(or 6 * 7 * 7 depending on the spatial jacobian). I can think of using std::vectorEigen::MatrixXd to allocate the output or alternatively just doing one $q_i$ at a time and computing the respective jacobian for the auto diff. In either case, I was struggling to pass it in the initializing the jacobian function.
I did the following to initialize autodiff
std::unique_ptr<multibody::MultibodyPlant<AutoDiffXd>> mplant_autodiff = systems::System<double>::ToAutoDiffXd(mplant);
std::unique_ptr<systems::Context<AutoDiffXd>> mContext_autodiff = mplant_autodiff->CreateDefaultContext();
mContext_autodiff->SetTimeStateAndParametersFrom(*mContext);
const multibody::Frame<AutoDiffXd>* mFrame_EE_autodiff = &mplant_autodiff->GetBodyByName(mEE_link).body_frame();
const multibody::Frame<AutoDiffXd>* mWorld_Frame_autodiff = &(mplant_autodiff->world_frame());
//Initialize the q as autodiff vector
drake::AutoDiffVecXd q_autodiff = drake::math::InitializeAutoDiff(mq_robot);
MatrixX<AutoDiffXd> mJacobian_autodiff; // Linear Jacobian matrix.
mplant_autodiff->SetPositions(context_autodiff.get(), q_autodiff);
mplant_autodiff->CalcJacobianTranslationalVelocity(*mContext_autodiff,
multibody::JacobianWrtVariable::kQDot,
*mFrame_EE_autodiff,
Eigen::Vector3d::Zero(),
*mWorld_Frame_autodiff,
*mWorld_Frame_autodiff,
&mJacobian_autodiff
);
However, as far as I understand, InitializeAutoDiff initializes to the identity matrix, whereas I want to $\partial{J}{q_i}$, so is there is a better way to do it. In addition, I get error messages when I try to call the jacobian matrix. Is there a way to address this problem both for $\partial{J}{q_i}$ for each q_i and changing q_i in a for loop or directly getting the result in a tensor. My apologies if I am doing something total tangent to the correct approach. I thank you in anticipation.
However, as far as I understand, InitializeAutoDiff initializes to the identity matrix, whereas I want to $\partial{J}{q_i}$, so is there is a better way to do it
That is correct. When you call InitializeAutoDiff and compute mJacobian_autodiff, you get a matrix of AutoDiffXd. Each AutoDiffXd has a value() function that stores the double value, and a derivatives() storing the gradient as an Eigen::VectorXd. We have
mJacobian(i, j).value() = J(i, j)
mJacobian_autodiff(i, j).derivatives()(k) = ∂J(i, j)/∂q(k)
So if you want to create a std::vecot<Eigen::MatrixXd> such that the k'th entry of this vector stores the matrix ∂J/∂q(k), then here is a code
std::vector<Eigen::MatrixXd> dJdq(q_autodiff.rows());
for (int i = 0; i < q_autodiff.rows(); ++i) {
dJdq[i].resize(mJacobian_autodiff.rows(), mJacobian_autodiff.cols());
}
for (int i = 0; i < q_autodiff.rows(); ++i) {
// dJidq stores the gradient of the ∂J.col(i)/∂q, namely dJidq(j, k) = ∂J(j, i)/∂q(k)
auto dJidq = ExtractGradient(mJacobian_autodiff.col(i));
for (int j = 0; j < static_cast<int>(dJdq.size()); ++j) {
dJdq[j].col(i) = dJidq.col(j);
}
}
Compute ∂J/∂q(i) for a single i
If you do not want to compute ∂J/∂q(i) for all i, but only for one specific i, you can change the initialization of q_autodiff from InitializeAutoDiff to this
AutoDiffVecXd q_autodiff(q.rows());
for (int k = 0; k < q_autodiff.rows(); ++k) {
q_autodiff(k).value() = q(k)
q_autodiff(k).derivatives() = Vector1d::Zero();
if (k == i) {
q_autodiff(k).derivatives()(0) = 1;
}
}
namely q_autodiff stores the gradient ∂q/∂q(i), which is 0 for all k != i and 1 when k == i. And then you can compute mJacobian_autodiff using your current code. Now mJacobian_autodiff(m, n).derivatives() store the gradient of ∂J(m, m)/∂q(i) for that specific i. You can extract this gradient as
Eigen::Matrix dJdqi(mJacobian_autodiff.rows(), mJacobian_autodiff.cols());
for (int m = 0; m < dJdqi.rows(); ++m) {
for (int n = 0; n < dJdqi.cols(); ++n) {
dJdqi(m, n) = mJacobian_autodiff(m, n).derivatives()(0);
}
}

ThinkOrSwim function equivalent in MQL

I have never heard of ThinkOrSwrim till yesterday when someone asked me to convert a ThinkOrSwim script to an MQL4 indicator.
A part of the code is as follows:
input length = 21;
input price = close;
input ATRs=1;
input trueRangeAverageType = AverageType.WILDERS;
def flag;
def EMA = ExpAverage(close, length);
def shift1 = ATRs * MovingAverage(trueRangeAverageType, TrueRange(high, close, low), length);
I want to ask you to kindly check and let me know if my understanding is correct.
input ATRs=1; // This should be a multiplier for ATR, then I think I should give it a double
//type for more flexible control.
input trueRangeAverageType = AverageType.WILDERS;
//As far as I understood, wilders is the same as SMMA in MQL.
.
def shift1 = ATRs * MovingAverage(trueRangeAverageType, TrueRange(high, close, low), length);
Here is the main piece of this code which I need your help with.
My understanding is as follows
ATRs ==>> Just a multiplier
I think the rest of this line is calculating the ATR, right?
If so, then I can see that I cannot simply convert this to iATR (in mql), because we are not able to choose MA Methode of ATR in mql4.
Then I think first I have to put the "True Range" of each bar in an array and then use this array as a price source to get the averages.
MQL4:
for(int i = 0; i < rates_total; i++)
{
data[i] = iATR(_Symbol, TF_1, 1, i);
}
for(int i = 0; i < limit; i++)
{
ExtBuffer[i] = iMAOnArray(data, 0, Inplenght, 0, InpMAMethod, i);
}
If I'm in the right way yet, Then I think the iATR period has to be 1, to have the TrueRange of each bar and not the average of the TrueRanges.
And then have the variable length (from thinkOrSwim inputs) as the period parameter for iMAOnArray.
I would appreciate any help with it.
Regards
Edit:
I forgot to ask you something,
why should the programmer who wrote this thinkscript code call this variable shift1?

Fast implementation of BWT in Lua

local function fShallowCopy(tData)
local tOutput = {}
for k,v in ipairs(tData) do
tOutput[k] = v
end
return tOutput
end
local function fLexTblSort(tA,tB) --sorter for tables
for i=1,#tA do
if tA[i]~=tB[i] then
return tA[i]<tB[i]
end
end
return false
end
function fBWT(tData)
--setup--
local iSize = #tData
local tSolution = {}
local tSolved = {}
--key table--
for n=1,iSize do
tData[iSize] = fRemove(tData,1)
tSolution[n] = fShallowCopy(tData)
end
table.sort(tSolution,fLexTblSort)
--encode output--
for i=1,iSize do
tSolved[i] = tSolution[i][iSize]
end
--finalize--
for i=1,iSize do
if fIsEqual(tSolution[i],tData) then
return i,tSolved
end
end
return false
end
Above is my current code for achieving BWT encoding in Lua. The issue is because of the size of the tables and lengths of loops it takes a long time to run. For a 1000 character input the average encoding time is about 1.15 seconds. Does anyone have suggestions for making a faster BWT encoding function?
the biggest slowdowns appear to be in fLexTblSort and fShallowCopy. I have included both above the BWT function as well.
If I see right, your algorithm has complexity O(n^2 log n), if the sort is quicksort. The comparator function fLexTblSort takes O(n) itself for each pair of values you compare.
As I checked with my implementation from few years back, I see possible space to improve. You create all the possible rotations of the tData, which takes also a lot of time. I used only single data block and I stored only starting positions of particular rotations. You also use a lot of loops which can shrink into less.
Mine implementation was in C, but the concept can be used also in Lua. The idea in some hybrid pseudocode between your Lua and C.
function fBWT(tData)
local n = #tData
local tSolution = {}
for(i = 0; i < n; i++)
tSolution[i] = i;
--table.sort(tSolution, fLexTblSort)
quicksort(tData, n, tSolution, 0, n)
for(i = 0; i < n; i++){
tSolved[i] = tData[(tSolution[i]+n-1)%n];
if( tSolution[i] == 0 )
I = i;
}
return I, tSolved
end
You will also need your own sort function, because the standard does not offer enough flexibility for this magic. Quicksort is a good idea (you might avoid some of the arguments, but I pasted just the C version I was using):
void swap(int array[], int left, int right){
int tmp = array[right];
array[right] = array[left];
array[left] = tmp;
}
void quicksort(uint8_t data[], int length, int array[], int left, int right){
if(left < right){
int boundary = left;
for(int i = left + 1; i < right; i++){
if( offset_compare(data, length, array, i, left) < 0 ){
swap(array, i, ++boundary);
}
}
swap(array, left, boundary);
quicksort(data, length, array, left, boundary);
quicksort(data, length, array, boundary + 1, right);
}
}
The last step is your own comparator function (similar to your original, but working on the rotations, again in C):
/**
* compare one string (fixed length) with different rotations.
*/
int offset_compare(uint8_t *data, int length, int *array, int first, int second){
int res;
for(int i = 0; i < length; i++){
res = data[(array[first]+i)%length] - data[(array[second]+i)%length];
if( res != 0 ){
return res;
}
}
return 0;
}
This is the basic idea I came up with few years ago and which worked for me. Let me know if there is something not clear or some mistake.

Bad Access/Pointer Issue in Objective-C

I've got the following bit of code:
Byte * tokenOut = NULL;
for (int i = 0; i < sizeof(Tknout); i++)
{
tokenOut[i * 2] = (Tknout[i] >> 8);
tokenOut[(i * 2) + 1] = (Tknout[i] & 0xFF);
}
But it generates an EXC_BAD_ACCESS error upon running when I try to update tokenOut. I'd appreciate if somebody could tell me what I'm doing wrong!
Thanks!
You are dereferencing a NULL pointer.
Try
Byte whatever;
Byte *outToken = &whatever;
// Do the rest.
Now there is valid memory for you to write to.
Except you will still have issues because you will write past the end of your variable. So maybe you wanted an array?
sizeof(outTkn) will return 1 (1 byte)

OpenCV - Display percentage instead of line [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
This is a application that can recognize emotions of happy/sad/anger/neutral/disgust/surprise.
The line will increase based on the current emotion that it recognize.
The link below is image of my current work , but I want to display percentage instead of line, but I not sure how.
http://postimg.org/image/j6hhe4dy7/
Anyone can help me with this would really appreciate.
Here is the part of code :
if(showTrackerGui) {
CvScalar expColor = cvScalar(0,254,0);
cvFlip(img, NULL, 1);
int start=12, step=15, current;
current = start;
for(int i = 0; i < N_EXPRESSIONS; i++, current+=step)
{
//this line display the emotion.
cvPutText(img, EXP_NAMES[i], cvPoint(5, current), &font, expColor);
}
expressions = get_class_weights(features);
current = start - 3;
for(int i = 0; i < N_EXPRESSIONS; i++, current+=step)
{
//this is the line which display the green line but I want to display percentage.
cvLine(img, cvPoint(80, current), cvPoint((int)(80+expressions.at<double>(0,i)*50), current), expColor, 2);
}
current += step + step;
if(showFeatures == 1)
{
for(int i=0; i<N_FEATURES; i++)
{
current += step;
char buf[4];
sprintf(buf, "%.2f", features.at<float>(0,i));
cvPutText(img, buf, cvPoint(5, current), &font, expColor);
}
}
}
}
Well, you can look at the line that prints the emotion titles which shows you exactly the method you want to call:
cvPutText(img, EXP_NAMES[i], cvPoint(5, current), &font, expColor);
And the line you want to change is:
cvLine(img, cvPoint(80, current), cvPoint((int)(80+expressions.at<double>(0,i)*50), current), expColor, 2);
So try replacing the line with cvLine() with the following:
// Assuming expressions.at<double>(0, i) returns a value between 0.0 and
// 1.0, convert it to 0.0 to 100.0.
double percentage = expressions.at<double>(0, i) * 100.0;
// Format the string buffer to hold "{percentage} %" (e.g., "50 %").
char buf[6]; // 3 bytes for the percentage, 1 for the space, 1 for the "%", 1 for the null byte.
sprintf(buf, "%3.f %%", percentage);
// Display percentage.
cvPutText(img, buf, cvPoint(80, current), &font, expColor);

Resources