Could we use uniroot() instead of optimize() for this minimization in R?
In the last line of my R code below, I use optimize()
to find the df2
that minimizes the ncp_diff
function.
However, I was wondering if I could uniroot()
instead of optimize()
for this minimization?
alpha = c(.025, .975); df1 = 3; peta = .3 # The input
f < function(alpha, q, df1, df2, ncp){ # Notice `ncp` is the unknown
alpha  suppressWarnings(pf(q = (peta / df1) / ((1  peta)/df2), df1, df2, ncp, lower = FALSE))
}
ncp < function(df2){ # Root finding: finds 2 `ncp` for a given `df2`
b < sapply(c(alpha[1], alpha[2]),
function(x) uniroot(f, c(0, 1e7), alpha = x, q = peta, df1 = df1, df2 = df2)[[1]])
b / (b + (df2 + 4))
}
ncp_diff < function(df2, target = 0.15){
the_ncp < ncp(df2)
return(abs(abs(the_ncp[2]  the_ncp[1])  target))
}
optimize(ncp_diff, c(0, 1000)) ## HERE can I use `uniroot()` instead of `optimize()`
1 answer

alpha = c(.025, .975); df1 = 3; peta = .3 # The input f < function(alpha, q, df1, df2, ncp){ # Notice `ncp` is the unknown alpha  suppressWarnings(pf(q = (peta / df1) / ((1  peta)/df2), df1, df2, ncp, lower = FALSE)) } ncp < function(df2){ # Root finding: finds 2 `ncp` for a given `df2` b < sapply(c(alpha[1], alpha[2]), function(x) uniroot(f, c(0, 1e7), alpha = x, q = peta, df1 = df1, df2 = df2)[[1]]) b / (b + (df2 + 4)) } ncp_diff < function(df2, target = 0.15){ the_ncp < ncp(df2) return((the_ncp[2]  the_ncp[1])  target) } uniroot(ncp_diff, c(100, 1000)) # $root [1] 336.3956 $f.root [1] 3.74663e09 $iter [1] 7 $init.it [1] NA $estim.prec [1] 6.103516e05
Edit:
In order to use the same interval of (0,1000) we can look for a way to go around a scenario where both the lower and upper values produce results on the same side of the number line. Since this is an error in r, we can go through it by
tryCatch
ncp < function(df2){ # Root finding: finds 2 `ncp` for a given `df2` b < sapply(c(alpha[1], alpha[2]), function(x) tryCatch(uniroot(f, c(0, 1e7), alpha = x, q = peta, df1 = df1, df2 = df2)[[1]], error =function(e)NA )) if(any(is.na(b)))b= c(1,10) b / (b + (df2 + 4)) } uniroot(ncp_diff, c(0, 1000)) # $root [1] 336.3956 $f.root [1] 2.132438e09 $iter [1] 8 $init.it [1] NA $estim.prec [1] 6.103516e05
See also questions close to this topic

R regression: Error in `[.data.frame`(data, , all.vars(Terms), drop = FALSE) :undefined columns selected
I've been trying to build regression models using different ways and method and as I was trying out this code here, using the Caret package:
library(caret) set.seed(222) ind < sample(2, nrow(model2), replace = T, prob = c(0.7,0.3)) train < model2[ind==1,] test < model2[ind==2,] custom < trainControl(method = "repeatedcv", number = 6, repeats = 6, verboseIter = T) lm < train(train$SS~., train, method = 'lm', trControl = custom) lm$results
But I kept receiving this error note:
Error in `[.data.frame`(data, , all.vars(Terms), drop = FALSE) :undefined columns selected
Here are the
str()
of my data set.> str(train) 'data.frame': 19 obs. of 15 variables: $ SST : num 0 0 0 0 1 0 0 0 0 1 ... $ SSA : num 0 1 0 0 0 0 0 1 0 0 ... $ SSR : num 0 0 0 1 0 0 0 0 0 0 ... $ SSC : num 0 0 0 0 0 0 0 0 0 1 ... $ SSF : num 1 1 1 0 1 1 1 1 1 1 ... $ SSS : num 0 0 0 1 0 0 0 0 0 0 ... $ SST : num 1 1 1 0 1 1 1 1 1 1 ... $ SSH : num 1 1 1 0 1 1 1 1 1 1 ... $ SSC : num 1 1 1 0 1 1 1 1 1 1 ... $ SSW : num 0 0 0 0 0 0 0 0 0 0 ... $ QTY : num 45 45 49 13 48 109 45 42 45 31 ... $ SS : num 470000 550000 460000 630000 1060000 530000 480000 510000 460000 630000 ... $ BASE..SS : num 6.27e+09 6.67e+09 6.14e+09 8.54e+09 1.43e+10 ... $ Ex : num 13341 13341 13341 13341 13341 ... $ TPH. : num 45 45 45 90 95 65 45 45 45 45 ...
Any kind of help will be greatly appreciated. Thank you for taking time off this question!

How to execute a function without argument using lapply
I have the following functions:
set.seed(1) make_seq < function() { paste0(sample(LETTERS, size = 30, replace = TRUE), collapse = "") } make_seq() #> [1] "GJOXFXYRQBFERJUMSZJUYFQDGKAJWI"
It takes no argument and spits out a sequence.
What I want to do is to compactly create 100 sequences with the above function with
lapply
. But why this failed?> lapply(1:100, make_seq()) Error in get(as.character(FUN), mode = "function", envir = envir) : object 'GJOXFXYRQBFERJUMSZJUYFQDGKAJWI' of mode 'function' was not found
What's the right way to do it?

ggplot change color of one bar from stacked bar chart
Is there way to change colors of one bar( x  value) manualy in
ggplot
data
for_plot_test=structure(list(name = c("A", "B", "C", "A1", "A2", "A3", "A4", "BI", "A", "B", "C", "A1", "A2", "A3", "A4", "BI"), n = c(1L, 3L, 5L, 7L, 9L, 11L, 13L, 15L, 2L, 4L, 6L, 8L, 10L, 12L, 14L, 16L), value = c(0, 0.05, 0, 0.05, 0.05, 0.1, 0.05, 0, 1, 0.7, 0.6, 0.5, 0.4, 0.2, 0.2, 0.1), variable = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L), .Label = c("PROGRESS", "prev_progress"), class = "factor")), class = c("grouped_df", "tbl_df", "tbl", "data.frame"), row.names = c(NA, 16L), vars = "name", labels = structure(list(name = c("Applications", "BI", "Clients", "CRE & Scoring", "Portfolio & Production", "SG Russia", "Transactions", "УКЛ & Prescoring")), row.names = c(NA, 8L), class = "data.frame", vars = "name", drop = TRUE, indices = list(0:1, 14:15, 6:7, 10:11, 2:3, 12:13, 8:9, 4:5), group_sizes = c(2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L), biggest_group_size = 2L, .Names = "name"), indices = list(c(0L, 8L), c(7L, 15L), c(3L, 11L), c(5L, 13L), c(1L, 9L), c(6L, 14L), c(4L, 12L), c(2L, 10L)), drop = TRUE, group_sizes = c(2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L), biggest_group_size = 2L, .Names = c("name", "n", "value", "variable"))
Current plot
colot_progress=c("#be877a","#dcbfad") s < ggplot(for_plot_test, aes(x= reorder(name, n),y = value, fill = variable,label=ifelse(for_plot$value==0,"",scales::percent(for_plot$value))))+ geom_bar(stat='identity',position = "stack")+ scale_fill_manual(values=colot_progress,aesthetics = "fill")+ coord_flip()+ theme_minimal() + theme( axis.title = element_blank(), axis.text.x=element_blank(), panel.grid = element_blank(), legend.position="none" )+ geom_text(size = 5, position = position_stack(vjust = 0.5)) s

Using filter in clojure function
Why
(filter even? (range 10))
gives (0 2 4 6 8)
but
((fn [x] filter even? x) (range 10))
gives
(0 1 2 3 4 5 6 7 8 9)
?

Why does sizeof(a) / sizeof(*a) fail to work when moved to a function in C?
#include <stdio.h> int main(void) { int a[3] = {11, 22, 33}; printf("%d\n", sizeof(a) / sizeof(*a)); return 0; }
Look at the above code, in which sizeof(a) / sizeof(*a) can be used to calculate how many elements are included in the array a.
I understand a in sizeof(a) represents a[].
Now I try to create a function called calnum to do that.
#include <stdio.h> int calnum(int *p); int main(void) { int a[] = {11, 22, 33}; printf("%d\n", calnum(a)); return 0; } int calnum(int *p) { int n; n = sizeof(p) / sizeof(*p); return n; }
Output is 2.
When I add more elements to array a, like a[] = {11, 22, 33, 44, 55, 566};
Output is always 2.
Why does sizeof(a) / sizeof(*a) fail to work when moved to a function ?

Eclipse C++ String as function parameter
I am having a problem with an error function which' purpose it is to check a variable and in a certain case tell me the variables name and its value.
I want to give the value as well as the name (as a string) to the function but I am having problems declaring a string somehow (Eclipse MinGW C++).
If anyone could point me to my mistake or show me a workaround that would be great!
This is the code:
#include <string> #include <iostream> using namespace std; int *ierr; std::string(varname); //problem here, doesnt recognize the string void error(double varvalue, std::string varname) { if (varvalue == 0 ) { *ierr = 11; cout << "Error: " << varname << " has an invalid value (equal 0)"; cout << "Error number " << *ierr << endl; return; } if (varvalue < 0 ) { *ierr = 10; cout << "Error: " << varname << " has an invalid value (" << varvalue << " , smaller 0)"; cout << "Error number: " << *ierr << endl; return; } } int main() { int Par = 0; error(Par,"Par"); //test variable }

scala: using function definitions
In the code below, the first function compiles. The second doesn't compile.
type FTDoubleDouble_Double = (Double, Double) => Double val _dividedBy: FTDoubleDouble_Double = { _ / _.toDouble } val _dividedByThenLog: FTDoubleDouble_Double = { val result1 = _ / _.toDouble scala.math.log(result1) }
The compilation error is
cannot resolve symbol /
I am sure this is basic, but I am a bit confused.

Best way to calculate Bernoulli's nTh numbers in C with CodeBlocks on Windows 10 Pro
Good night, I'm working in a project that needs to calculate the Bernoulli numbers for nTh order. I tried exhaustively a lot of algorithms on internet, mostly it's in C++ what's not usefull for me. And always I'd got compilations erros or the wrong results to the numbers! What is the fastest way to calculate it? Odd's numbers is always 0.00000 and I need to calculate for any even numbers... I just need the result of the number I put on the function, don't need to list the numbers until the nTh like every algorithm I saw on the internet does. The last I tried that had compilation erros and after fixed give me wrong answers above... Yes, for people that will ask me if I put the libraries on the code, yes, I did it! The problem is not libraries, it's wrong algorithms. I'm using C on GCC mingw 32bits on Code::Blocks for Windows 10 Pro.
#include <float.h> #include <math.h> void bernoulli_B( int iMax, double* dB ) { dB[0] = 1.0; dB[1] = 0.5; for( int j = 3; j <= iMax; j += 2 ) dB[j] = 0.0; const double eps = DBL_EPSILON; const double TwoPi = 6.2831853071795860; double dCoeff = 2.0 / (TwoPi * TwoPi); double d2 = 2.0; for( int n = 1; n <= iMax/2; n++ ) { double g1 = 1.0, g2 = 1.0; for( int j = 0; j < n; j++ ) { g1 *= 4.0; g2 *= 9.0; } double S1 = 1.0  1.0/g1, S2 = S1 + 1.0/g2, S3; double T1 = S1 + 1.0/(g2 + g1), T2; long r = 4; double s = 1.0; int nSuccess = 0; while( !nSuccess ) { double r2 = double(r*r); double g3 = 1.0; for( int j = 0; j < n; j++ ) g3 *= r2; S3 = S2 + s/g3; T2 = S2 + s/(g3 + g2); if( fabs(T2T1) > eps*fabs(T2) ) { g2 = g3; S2 = S3; T1 = T2; s = s; r++; } else { nSuccess = 1; } } d2 /= 4.0; dB[2*n] = 2.0 * dCoeff / (1.0d2) * T2; dCoeff *= double((2*n+1)*(2*n+2)) / (TwoPi * TwoPi); } }
I've never worked with this type of stuff before, but on the series I'am working requires the Bernoulli numbers. So I don't have many sure what I'm doing to find those numbers. It's not my area. Probably I made some stupid thing here.
I'll tell you how I fall in this problem of Bernoulli, I'm originally working on Riemann Zeta's function. I made the C code but it only worked for >1, So I started to study how to calculate for Negative odd's, and I saw that Bn(Bernoulli numbers of N order) are in the formulae! I don't know how to calculate Bernoulli Numbers, and when I started to code Zeta's function I didn't know nothing about Bernoulli!

Fastest Bernoulli numbers calculation in C using (or not) GMP in CodeBlocks on Windows
Good night, I'm working in a project that needs to calculate the Bernoulli numbers for nTh order. I tried exhaustively a lot of algorithms on internet, mostly it's in C++ what's not usefull for me. And always I'd got compilations erros or the wrong results to the numbers! What is the fastest way to calculate it? Odd's numbers is always 0.00000 and I need to calculate for any even numbers... I just need the result of the number I put on the function, don't need to list the numbers until the nTh like every algorithm I saw on the internet does. The last I tried that had compilation erros and after fixed give me wrong awnsers was. Completely wrong numbers! Yes, for people that will ask me if I put the libraries on the code, yes, I did it! The problem is not libraries, it's wrong algorithms. I'm using C on GCC mingw 32bits on Code::Blocks for Windows 10 Pro.
http://www.codecogs.com/library/maths/discrete/number_theory/bernoulli_b.php
Thanks you all! Have a nice day.

How to test existing Angularjs overall performance (DOM rendering)?
I got an existing angularjs project for optimization. How can I find gaps like (memory leakage, performance on browser , Data rendering , screen got stuck kind of issues). I tried Jmeter but its not showing javascript performance just shows page is navigated in few Milli seconds. I tried to find with chrome profiling , I got some specific scenarios but not overall image.
How can I get overall performance results?

Python ifelifelse runtime optimization
I did a search on the previous asked question, but without finding what i need to optimize my code.
For info, I am running on Python 2.7 but could change to 3 if needed
I am converting every pixel of an image and because of some condition i have to do it pixel by pixel. So i have nested for loop with an ifelifelse statement inside, and it takes an awful long time to run. For an image of 1536 x 2640, the whole code takes ~20 seconds and 90% of time is inside this double for loop
I believe there should be a better way to write the below code
for pixel in range(width): for row in range(height): ADC = img_original[row, pixel] if ADC < 84: gain = gain1 offset = offset1 elif ADC > 153: gain = gain3 offset = offset3 else: gain = gain2 offset = offset2 Conv_ADC = int(min(max(ADC * gain + offset, 0),255)) img_conv[row, pixel] = Conv_ADC
Thanks for the help
edit for additional detail:
@JeanFrançoisFabre is right and I am applying three different gain/offset depending on which section I am between 0 to 255. But the section are not always evenly space and can be modified. Maybe to give some additional context, i am simply applying a custom Scurve to an image to shift the pixel value up/down. And each column in the image have their own Scurve
my gain1,2,3/offset1,2,3 values are floating point. the gain will always be positive and the offset can be negative or positive.I also have an individual value for each pixel in the width direction, but they are common in the row direction.
Example, all pixel from column 1 with can use gain/offset 1,2,3 from the 1st row in table below. All pixel from column 2 in the image will use gain/offset form the row 2 in the table below
Pixel G1 O1 G2 O2 G3 O3 1 0.417722 24.911392 0.623188 7.652176 1.175676 76.878357 2 0.43038 25.848103 0.623188 9.652176 1.148649 70.743225 3 0.443038 23.784809 0.637681 7.434776 1.175676 74.878357 4 0.443038 22.784809 0.652174 5.217384 1.175676 74.878357 5 0.455696 23.721519 0.637681 8.434776 1.202703 78.013519 6 0.455696 21.721519 0.637681 6.434776 1.243243 86.216217 7 0.455696 22.721519 0.623188 8.652176 1.216216 82.081085 8 0.443038 22.784809 0.623188 7.652176 1.22973 85.148651 ... until pixel 2640 in width direction
I will look at @JeanFrançoisFabre solution, but in the meantime i was also looking at using some numpy approaches.
Once i get something that compute faster, i'll post my finding here

Optimization issue using Optim in R
I´m still learning how to use Optim resource in R. I have this function below that I would like to minimize the MSE changing two paramenters (k and l) but I found this error message: "Error in fn(par, ...) : argument "k" is missing, with no default"
code:
age = c(7,14,21,28,35) weight = c(0.190,0.500,0.900,1.6,2.25) fr < function(l,k,age,weight)sqrt(sum(abs(weight(0.05*exp((l/k)*(1exp(k*age)))))^2)) optim(c(0.21,0.045), fr, age=age, weight=weight)
thanks

Parameter "triangulatedPoints" of recoverPose and math behind it
cv::recoverPose has parameter "triangulatedPoints" as seen in documentation, though math behind it is not documented, even in sources (relevant commit on github). When I use it, I get this matrix in following form:
[0.06596200907402348, 0.1074107606919504, 0.08120752154556411, 0.07162400555712592, 0.1112415181779849, 0.06479560707001968, 0.06812069103377787, 0.07274771866295617, 0.1036230973846902, 0.07643884790206311, 0.09753859499789987, 0.1050111597547035, 0.08431322508162108, 0.08653721971228882, 0.06607013741719928, 0.1088621999959361, 0.1079215237863785, 0.07874160849424018, 0.07888037486261903, 0.07311940086190356; 0.3474319603010109, 0.3492386196164926, 0.3592673043398864, 0.3301695131649525, 0.3398606744869519, 0.3240186574427479, 0.3302508442361889, 0.3534091474425142, 0.3134288005980755, 0.3456284001726975, 0.3372514921152191, 0.3229005408417835, 0.3156005118578394, 0.3545418178651592, 0.3427899760859008, 0.3552801904337188, 0.3368860879000375, 0.3268499974874541, 0.3221050630233929, 0.3395139819250934; 0.9334091581425227, 0.9288726274060354, 0.9277125424980246, 0.9392374374147775, 0.9318967835907961, 0.941870018271934, 0.9394698966781299, 0.9306592884695234, 0.9419749503870455, 0.9332801148509925, 0.9343740431697417, 0.9386198310107222, 0.9431781968459053, 0.9290466865633286, 0.9351167772249444, 0.9264105322194914, 0.933362882155191, 0.9398254944757025, 0.9414486961893244, 0.935785675955617; 0.0607238817598344, 0.0607532477465341, 0.06067768097603395, 0.06075467523485482, 0.06073245675798231, 0.06078081616640227, 0.06074754785132623, 0.0606879948481664, 0.06089198212719162, 0.06071522666667255, 0.06076842109618678, 0.06083346023742937, 0.06084805655000008, 0.0606931888685702, 0.06071558440082779, 0.06073329803512636, 0.06078189449161094, 0.06080195858434526, 0.06083228813425822, 0.06073695721101467]
e.g. 4x20 matrix (in this case there were 20 points). I want to convert this data to std::vector in order to use it in solvePnP. How to do it, what is the math here? Thanks!

Solve Underdetermined System of Equations for Sparse Solution
 A, C are m x n rectangular matrix.
 B is a n x n square matrix.
 B is not symmetric.
 B, C are known
 AB = C.
 B is singular.
I could use the moorepenrose inverse of B to get A = CB^{+}.
But that seems to make A have many nonzero elements.
If I want an A (among all possible solutions) that is quite sparse, what solvers can I try?
Should I use BDCSVD, as in here?
Thanks.

A Solution from infinite solutions within a range
Suppose I have a system of equations whose augmented matrix is $$ \begin{bmatrix} 1 & 2 & 3 & 7\ 4 & 5 & 6 & 8 \ \end{bmatrix} $$ After converting this matrix to row reduced echelon form I got $$ \begin{bmatrix} 1 & 0 & 1 & 19/3\ 0 & 1 & 2 & 20/3 \ \end{bmatrix} $$
Now I want a solution such that $$0 < x_1 < 9$$ , $$0 < x_2 < 7$$ and $$0 < x_3 < 2$$ One such solutions is x_1 = 16/3 , x_2 = 14/3 and x_3 = 1.
But how do I find one such solution in general case, suppose I have n unknowns variables ? I am only considering the case when infinite solutions exist for a linear system.